Sorry my bad english.
My code in C#.
I have variable:
Type t = /* Variable with any unknown type */
And i need in used template:
var b = GetData</* I need used variable t in here */>();
How do it?
OR
I need variable
object c = /*any data*/
Type type = /*any type*/
I need this:
var b = (type)c;
How do it?
In this case if c could actually be a different type but is convertible then you can use something like this.
For example "123" is a string but convertible to an integer.
object c = "123";
Type type = typeof(int);
var b = Convert.ChangeType(c, type);
Related
In C#, given two input Types, it it possible to determine the output Type and implicit upcast Types for an operator? For example, consider the expression s + i. Say I have the following information:
short s;
int i;
Type leftType = typeof(short);
Type rightType = typeof(int);
Can I determine the following information about the expression s + i?
Type leftUpcastType = typeof(int);
Type rightUpcastType = typeof(int);
Type outputType = typeof(int);
I obviously could do this with an enormous lookup table of all the types and operators, but there might be an easier way. Ideally this would work for user-defined classes with operator overloads too, but that is a secondary requirement.
Yes, you can achieve this using the dynamic Type. Keep in mind, though, that dynamic will throw an exception for anything that can't be summed at runtime so you will need to ensure that you are only passing valid values or wrap in a try/catch.
var leftType = left.GetType();
var rightType = right.GetType();
var outputType = ((dynamic)left + (dynamic)right).GetType();
You can then infer from this information whether one, both or neither of the objects were converted for the operation.
The best way to do this is to examine the return type of an expression that adds two values of the types you're interested in. This way you don't need to worry about providing valid values for the addition at runtime, when all you care about is the return type.
You can either take an existing expression and walk down the expression tree if one is available to you, or do something like this:
static Type GetTypeOfSummation<T1, T2>()
{
var p1 = Expression.Parameter(typeof(T1), "t1");
var p2 = Expression.Parameter(typeof(T2), "t2");
LambdaExpression x = DynamicExpression.ParseLambda(new[] { p1, p2 }, null, "t1 + t2");
return x.Body.Type;
}
static void Main()
{
Console.WriteLine(GetTypeOfSummation<int, double>()); // System.Double
Console.WriteLine(GetTypeOfSummation<int, decimal>()); // System.Decimal
Console.WriteLine(GetTypeOfSummation<float, double>()); // System.Double
}
This generic method will return the type of the addition operation without actually performing the addition.
You can of course do this with Type instances instead of generic type parameters as well, if that's what you want:
static Type GetTypeOfSummation(Type t1, Type t2)
{
var p1 = Expression.Parameter(t1, "t1");
var p2 = Expression.Parameter(t2, "t2");
LambdaExpression x = DynamicExpression.ParseLambda(new[] { p1, p2 }, null, "t1 + t2");
return x.Body.Type;
}
To be clear, DynamicExpression is from the System.Linq.Dynamic namespace, which you can obtain by referencing: https://www.nuget.org/packages/System.Linq.Dynamic/
Is it possible to cast a type definition in C#? Such as the following:
Type t = typeof(Activity) as typeof(System.Data.Entity.DbSet<MyDomain.Activity>)
Or trying to force a cast:
Type t2 = typeof(System.Data.Entity.DbSet<MyDomain.Activity>) typeof(Activity);
I want to create a type definition System.Data.Entity.DbSet<MyDomain.Activity>
I'm doing this because I'm using reflection on my domain, trying to pull on the properties on the context, in case anyone asks.
// get types we are interested in IHit
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(IHit))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as IHit;
// loop and cast
foreach (var instance in instances)
{
Type t = instance.GetType()
Type t2 = typeof(System.Data.Entity.DbSet<t>) as typeof(t);
// do something with type 2
}
I want to create a type definition System.Data.Entity.DbSet<MyDomain.Activity>
So you are actually asking t to be the type of System.Data.Entity.DbSet<MyDomain.Activity>. Why do you need to cast one type of another? The type MyDomain.Activity doesn't have to do anything with the type you are actually requesting.
This should work for you:
Type t = typeof(System.Data.Entity.DbSet<MyDomain.Activity>)
If you don't have the type of MyDomain.Activity yet, you should use Type.MakeGenericType:
Type dbSetType = typeof(System.Data.Entity.DbSet<>);
Type t = dbSetType.MakeGenericType(yourActivityType);
I know that I can use the type string as:
string someString = "This is my string";
I am not sure how to use the type Type
Type someType = someString.GetType();
How could I create a variable based on that type. I want to do something like
someType someOtherString = "here is another string";
//string
In other words, how could I create a variable based on some type?
There are a few ways to go about this, but the simplest would be to use the Activator class.
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
Example:
Type t = someClassInstance.GetType();
object o = Activator.CreateInstance(t);
Variable types have to be known at declaration time. You can declare a variable of type object and then dynamically create an instance of a type which you only know about at execution time, but you can't dynamically declare a variable like that.
The closest you could get would be to create a generic type and instantiate that using a type argument specified with reflection. Then you really would have a variable of the right type - but you wouldn't be able to do anything particularly useful with it.
It's important to distinguish between the type of a variable and the type of the object a variable's value may refer to. For example:
object foo = Activator.CreateInstance(someType);
will end up with a variable of type object, but the value of foo will be a reference to an instance of whatever type someType refers to.
Try
var object = Activator.CreateInstance(myType);
Starting from C# 3 you can do:
var someOtherString = "here is another string";
This way you don't care what's the type, var is type "joker" and save you the need to know the type at declaration time.
Hope that's what you mean?
use Assembly.CreateInstance()
Type type = typeof(String);
Assembly asm = Assembly.GetExecutingAssembly();
object blah = asm.CreateInstance(type.FullName);
Is there a way in C# to cast an object based on a string?
Example,
String typeToCast = control.GetType().Name;
Button b = (typeToCast)control;
Yes you can but you should not.
Csharp
string value = "2.5";
object typedObject;
typedObject = Convert.ChangeType(value, Type.GetType("System.Double"));
Vbnet
Dim value As String = "2.5"
Dim typedObject As Object
typedObject = Convert.ChangeType(value, Type.GetType("System.Double"))
No, you can't do that. Also, what would you achieve, as you have to assign it to "static" type, in your case, it's Button - So why not just cast it normally:
Button b = (Button)control;
You can hovewer, check if your control is of a type:
Type t = TypeFromString(name);
bool isInstanceOf = t.IsInstanceOfType(control);
Edit:
To create an object without having it type at compile time, you can use Activator class:
object obj = Activator.CreateInstance(TypeFromString(name));
Button button = (Button)obj; //Cast to compile-time known type.
Suppose you create a generic Object variable and assign it to a specific instance. If you do GetType(), will it get type Object or the type of the original class?
Yes.
You can also do:
object c = new FooBar();
if(c is FooBar)
Console.WriteLine("FOOBAR!!!");
Short answer: GetType() will return the Type of the specific object. I made a quick app to test this:
Foo f = new Foo();
Type t = f.GetType();
Object o = (object)f;
Type t2 = o.GetType();
bool areSame = t.Equals(t2);
And yep, they are the same.
Calling GetType() will call the ACTUAL type. If you want to know the base type, you can call GetType().BaseType