Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type casting method (.Net)

Tags:

c#

.net

types

I'm trying to create a generic method to cast an object, but can't seem to crack that chestnut. (It's Friday 3pm, been a long week)

Ok, so I have this scenario:

// We have a value (which .net sets as a double by default)
object obj = 1.0;

// We have the target type as a string, which could be anything:
// say string sometType = "System.Decimal"
Type type = Type.GetType(someType);

// I need a generic way of casting this
object castedObj = (xxx) obj;

How can I cast that object generically without creating an endless number of if-else-staments?

like image 268
André Haupt Avatar asked Oct 23 '09 13:10

André Haupt


People also ask

What are generic methods in C#?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.

Is generic type-safe in C#?

Generics are type safe because generics are available at run time, It means the runtime knows what type of data structure you're using and can store it in memory more efficiently.

Can we have generic method in non generic class in C#?

Yes, There are two level where you can apply generic type . You can apply generic type on Method level as well as Class level (both are optional).

What is generic in asp net C#?

Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.


2 Answers

You can use Convert.ChangeType method, if the types you use implement IConvertible (all primitive types do).

    Convert.ChangeType(value, targetType);
like image 82
Pop Catalin Avatar answered Sep 19 '22 18:09

Pop Catalin


Have a look at the Convert.ChangeType method, I think it will meet your needs.

like image 35
Jamie Ide Avatar answered Sep 21 '22 18:09

Jamie Ide