C# templated / generic method at compile time error - c#

I am working in c# with .net 2.0 (i know its old)
Here is my setup:
struct propertyType
{
System.type type;
}
public class DataProperties
{
private Dictionary<propertyType, object> properties;
public void setProperty(propertyType key, object value)
{
if(value.getType == key.type) //make sure they are adding valid data
properties.add(key, value);
}
public T getProperty<T> (propertyType key)
{
return (T)properties[key];
}
}
Then in my class that needs to pull properties it would look like
//this would be declared somewhere else for use by multiple classes.
//but for example sake its here
propertyType hash;
hash.type = typeof(byte[]);
byte[] hashCode = DataSet.properties.GetProperty<hash.type>(hash);
Now the last line is the one that doesnt work, but I'd like to work. I think the problem is that it doesnt like having a variable as the Type. In actual use there will be many different PropertyType objects so I want a way to get the properties out and cast to the correct type easily.
Does anyone know if it is for sure that the variable as the type is the problem. But at compile time it will know what hash.type is so its not that its an unknown value at compile time.

No, it is an unknown value at compile-time, as far as the compiler is concerned. Just because you've set it in the previous line doesn't mean the compiler really knows the value.
You simply can't use variables to specify type arguments in C# generics, other than with reflection. A type argument has to be the name of a type or another type parameter - it can't be an expression which evaluates to a System.Type.

the problem is that it doesnt like having a variable as the Type
That's right. There's no way to do this that keeps compile-time safety. It's possible to use reflection to call the getProperty method with a generic type that you only know at run time, but generics don't gain you anything in this case.
Since you're only using generics to do a type cast, why not add an overload to getProperty that's not generic and returns object?

As Jon Skeet and others have said, this cannot be done without reflection. So, here's some reflection code that should get you on the right track:
Type myGenericParam = typeof(byte[]);
MethodInfo method = typeof(DataProperties).GetMethod("getProperty").MakeGenericMethod(new[] { myGenericParam });
DataProperties foo = new DataProperties();
byte[] result = (byte[])method.Invoke(foo, new[] { /*parameters go here in order */ });

Related

Get the actual type from a Type variable

I am trying to get a type from a Type variable. For example:
Type t = typeof(String);
var result = SomeGenericMethod<t>();
An error happens on the second line, because t is not a type, it's a variable. Any way to make it a type?
To make an instance of a generic based on a Type, you can use reflection to get an instance of the generic with the type you want to use, then use Activator to create that instance:
Type t = typeof (string); //the type within our generic
//the type of the generic, without type arguments
Type listType = typeof (List<>);
//the type of the generic with the type arguments added
Type generictype = listType.MakeGenericType(t);
//creates an instance of the generic with the type arguments.
var x = Activator.CreateInstance(generictype);
Note that x here will be an object. To call functions on it, such as .Sort(), you'd have to make it a dynamic.
Please Note that this code is hard to read, write, maintain, reason about, understand, or love. If you have any alternatives to needing to use this sort of structure, explore those thoroughly.
Edit: You can also cast the object you receive from the Activator, such as (IList)Activator.CreateInstance(genericType). This will give you some functionality without having to resort to dynamics.
No, you cannot know the value of a Type object at compile time, which is what you would need to do in order to use a Type object as an actual type. Whatever you're doing that needs to use that Type will need to do so dynamically, and not require having a type known at compile time.
An ugly workaround using reflection:
Class with generic Method
public class Dummy {
public string WhatEver<T>() {
return "Hello";
}
}
Usage
var d = new Dummy();
Type t = typeof(string);
var result = typeof(Dummy).GetMethod("WhatEver").MakeGenericMethod(t).Invoke(d, null);
On class instantiation see Max's solution

Expression.Convert(..., someGenericType) throws ArgumentException when used with generic type

I have this method, using Expressions to create fields getters:
public static Func<object, T> CreateFieldValueGetter<T>(this Type declaringType, FieldInfo fieldToGet) {
var paramExp = Expression.Parameter(typeof(object));
// ArgumentException if declaringType describes generic-type:
var cast = Expression.Convert(paramExp, declaringType);
var body = Expression.Field(cast, fieldToGet);
return Expression.Lambda<Func<object, T>>(body, paramExp).Compile();
}
It works great until I give it a generic type like:
class DataErrorNotifyingViewModelBase<TErr> : ViewModelBase, INotifyDataErrorInfo
where TErr : struct, IConvertible, IComparable, IFormattable
{
// ...
}
This way:
var vm = new DataErrorNotifyingViewModelBase<MyErrorsTypeEnum> ();
var type = vm.GetType();
// ArgumentException:
var getter = type.CreateFieldValueGetter<PropertyChangedEventHandler>(type.GetField("PropertyChanged"));
This is the exception I get:
Exception thrown: 'System.ArgumentException' in System.Core.dll
Additional information: Type GuiHelpers.DataErrorNotifyingViewModelBase`1[TErr] is a generic type definition
although simple casting works:
var vm = new DataErrorNotifyingViewModelBase<PrintDialogError>();
var obj = (object) vm;
So how can I feed it with generic types? Am I limited to non-generic-types only?
Edit - solution:
Kaveh Hadjari caught it:
Passing t = typeof (Dictionary<T, int>) will raise ArgumentException, as t.GetGenericArguments()[0].IsGenericParameter is true (albeit t.GetGenericArguments()[1].IsGenericParameter is false!)
Passing the type t = typeof (Dictionary<int, int>) works fine, becuse no element of the t.GetGenericArguments() array has IsGenericParameter == true
A generic type is a template for many different specialized types, and at runtime theres a difference between the generic type and the "instanced" types. A possible reason the call to Expression.Convert might be failing could be you're providing it with the type of the generic version and not with a specialized version with type variables set.
Update: I imagine there's a good reason this method would never work with generic types. Consider the case if the type variable is used as type for a field in the generic class. Since the type size (reference, Boolean, short, int, long, etc) could be variable it would mean that it could offset the memory address of other fields in different specializations of the generic class in a variable way. How would you know in advance which field length thus address offset would be the case if all the variables where not set? You couldn't and therefor we can't determine the the address of the field we might want to create a getter for. The only solution would be to actually create a getter that would rely on using reflection on each object you call the getter with, which would incur higher costs than imagined and if you are happy with that solution you might be as well have a single method that gets the value of the field using reflection without actually creating these getters in the first place.
"Am I limited to non-generic-types only?"
No, of course not. The error message is clear, though not consistent with the code example you provided. You seem to be passing for the type the original generic type definition (i.e. with an unspecified value for the type parameter), not the constructed generic type (i.e. with a specified value for the type parameter).
Unfortunately, without a good, minimal, complete code example that reliably reproduces the problem, it's impossible to know precisely what you've done wrong. All I can say is that you did do something wrong. If you want more specific advice than that, please edit your post so that it includes a good code example.
For what it's worth, here's a complete code example that demonstrates your method working fine with a generic type:
class A<T>
{
public int field1;
public T field2;
public event EventHandler Event1;
}
class Program
{
static void Main(string[] args)
{
A<bool> a = new A<bool>();
Func<object, int> field1Getter =
CreateFieldValueGetter<int>(a.GetType(), a.GetType().GetField("field1"));
Func<object, bool> field2Getter =
CreateFieldValueGetter<bool>(a.GetType(), a.GetType().GetField("field2"));
Func<object, EventHandler> event1Getter =
CreateFieldValueGetter<EventHandler>(a.GetType(), a.GetType()
.GetField("Event1", BindingFlags.NonPublic | BindingFlags.Instance));
}
static Func<object, T> CreateFieldValueGetter<T>(Type declaringType, FieldInfo fieldToGet)
{
var paramExp = Expression.Parameter(typeof(object));
// ArgumentException if declaringType describes generic-type:
var cast = Expression.Convert(paramExp, declaringType);
var body = Expression.Field(cast, fieldToGet);
return Expression.Lambda<Func<object, T>>(body, paramExp).Compile();
}
}
The only wrinkle here is that to obtain the field for the event, you have to specify the BindingFlags appropriate to that field (in particular, it's non-public so the default search of GetField() won't find it). The code you showed does this incorrectly, but it doesn't explain the exception you're getting.

Reflection c# in a set property

Why can't I use the value word in a set property when i'm trying to get the type of the value?
set
{
Type t = value.GetType();
if (dictionaries[int.Parse(value.GetType().ToString())] == null)
{
dictionaries[int.Parse(value.GetType().ToString())] = new Dictionary<string,t>();
}
}
It doesn't recognize the word t in my Dictionary constructor.
what am I doing wrong? how can I solve it?
You cannot use values or names of types as generic type parameters. Use a method with a generic type parameter instead:
void SetDict<T>(T value)
{
Type t = typeof(T);
if (dictionaries[t.FullName] == null)
{
dictionaries[t.FullName] = new Dictionary<string,T>();
}
}
Instead of using the type name, you can also use the Type value as a key directly for dictionaries:
Dictionary<Type, Dictionary<string,T>> dictionaries;
You can call it without specifying the generic type parameter, because the compiler can infer the type. However, this works only for the static type, not for the runtime type. I.e. you must call the method with an expression of the right type and not through a base type like object.
SetDict("hello"); // ==> string type
SetDict(42); // ==> int type
object obj = "world";
SetDict(obj); // ==> object type, not string type!
Note: Generic type parameters allow you to create strongly typed specialized types and methods at compile time. The advantage of strong typing lies in the fact that the compiler and the IDE can give you information on a type and certify that your code is statically correct AT COMPILE TIME. Creating a generic type at RUNTIME has no advantage, as you won't be able to use its advantages at compile time (or design time, if you prefer). You can as well use a Dictionary<string, object> or the like.
Please see my answer on code review: Type-safe Dictionary for various types. Especially my update to the answer.
You can't use a Type variable when declaring a generic type, you have to use an actual type.
In other words, this won't work:
Type t = ....
var x = new Dictionary<string, t>();
Depending on your class, you could do this:
public class Something<T>
{
public T Value
{
...
set
{
... new Dictionary<string, T>();
}
}
}
but that's not quite the same.
You also got a different problem, this:
int.Parse(value.GetType().ToString())
will not work.
value.GetType().ToString()
will likely produce something like System.Int32 or YourAssembly.NameSpace.SomeType, not a number that can be parsed.
I think you need to take one step back, and figure out what you're trying to accomplish here.

Using reflection with generic types and implicit conversions

I'm trying to use reflection to set properties on some OpenXML types (e.g. Justification). Assigning a value by enumerating all possibilities is straight-forward:
// attr is an XmlAttribute, so .Name and .Value are Strings
if (attr.Name == "Val")
{
if (element is Justification)
{
((Justification)element).Val = (JustificationValues)Enum.Parse(typeof(JustificationValues), attr.Value);
return;
}
else
{
// test for dozens of other types, such as TabStop
}
}
What makes this difficult to do via reflection is:
1) The type of the Val property is EnumValue<T>, so I don't know how to extract the type to pass as the first argument to Enum.Parse.
2) There is an implicit conversion from the actual enumeration type to the EnumValue<> type, which I don't know how to invoke with reflection.
I would like the code to end up looking something like:
PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = ConvertToPropType(pInfo.PropertyType, attr.Value); /* this
would return an instance of EnumValue<JustificationValues> in this case */
pInfo.SetValue(element, value, null);
How do I implement ConvertToPropType? Or is there a better solution?
Thanks
Edit:
I got a solution working using Earwicker's suggestion, but it relies on the convenient fact that the enumeration's type name can be derived from the node's type name ("Justification" -> "JustificationValues"). I'm still curious how to solve this in the general case, though.
Edit2:
GetGenericArguments got me the rest of the way there. Thanks.
If the attribute value is just a string, I assume you already have some way of figuring out that the string identifies a value from a specific enumeration. In your example you have it hard-coded, so I'm not sure if that's what you want or what you want to change.
Assuming you know it's an enumeration, and you know which enumeration, you already know how to get an object containing a boxed value of the right enum type, as in your snippet.
Now if I assume EnumValue<T> has a constructor that takes a T.
Type genericType = typeof(EnumValue<>);
Type concreteType = genericType.MakeGenericType(typeof(JustificationValues));
Now concreteType is the type EnumValue<JustificationValues>.
From that you can get a constructor, hopefully one that takes a JustificationValues parameter, and Invoke it.
Update
Ahh, I see what you're doing now. You use the XML attribute name to pick a C# property. You need to be able to detect whether that property is of a type EnumValue<T>, and find out what T is.
PropertyInfo p = // ... get property info
Type t = p.GetType();
if (t.IsGenericType &&
t.GetGenericTypeDefinition == typeof(EnumValue<>))
{
Type e = t.GetGenericArguments()[0]; // get first (and only) type arg
// e is the enum type...
Give that a try.
.Net 4.0 adds support to do a late bound implict or explict conversion. This is simplified in the open source framework ImpromptuInterface with it's static method called InvokeConvert. In your ideal example it would work like this:
PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = Impromptu.InvokeConvert(attr.Value, pInfo.PropertyType);
pInfo.SetValue(element, value, null);
This might only work with basic types but it was good enough for what I'm doing
PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = System.Convert.ChangeType(attr.Value, pInfo.PropertyType);
pInfo.SetValue(element, value, null);

How to generate an instance of an unknown type at runtime?

i've got the following in C#:
string typename = "System.Int32";
string value = "4";
theses two strings should be taken to generate an object of the specified type with the specified value...
result should be:
object o = CreateUnknownType(typename, value);
...
Int32 test = (Int32)o;
Is this what are you are thinking?
object result = Convert.ChangeType("4", Type.GetType("System.Int32"));
As stated, this is too broad and can not be solved generally.
Here are some options:
Type type = Type.GetType(typename);
object o = Activator.CreateInstance(type);
This will create an instance of the type that typename is describing. It calls the parameterless constructor of that type. (Downside: Not all objects have a parameterless constructor. Further, this does set the state of the object using value.)
Type type = Type.GetType(typename);
object o = Activator.CreateInstance(type, new[] { value });
This will create an instance of the type that typename is describing. It calls a constructor of that type that accepts one parameter of type string. (Downside: Not all objects have such a constructor. For example, Int32 does not have such a constructor so you will experience a runtime exception.)
Type type = Type.GetType(typename);
object o = Convert.ChangeType(value, type);
This will attempt to convert the string value to an instance of the required type. This can lead to InvalidCastExceptions though. For example, Convert.ChangeType("4", typeof(FileStream)) will obviously fail, as it should.
In fact, this last example (create an instance of type FileStream with its initial state determined by the string "4") shows how absurd the general problem is. There are some constructions/conversions that just can not be done.
You might want to rethink the problem you are trying to solve to avoid this morass.
Creating an instance of a type you know by name (and which should have a default constructor):
string typeName = "System.Int32";
Type type = Type.GetType(type);
object o = Activator.CreateInstance(type);
Parsing a value from a string will obviously only work for a limited set of types. You could
use Convert.ChangeType as suggested
by PhilipW
or maybe create a
Dictionary<Type,Func<string,object>>
which maps known types to known parse
functions
or use reflection to invoke the
Parse(string) method on the type,
assuming there is one:
string valueText = "4";
MethodInfo parseMethod = type.GetMethod("Parse");
object value = parseMethod.Invoke(null, new object[] { valueText });
or maybe you can use the
infrastructure provided by the .NET
component model. You can fetch the
type converter of a component and use
it like this:
TypeConverter converter = TypeDescriptor.GetConverter(type);
object value = converter.ConvertFromString(valueText);
Your logic seems a little flawed here. Obviously, if you're directly casting the object at a later time to the actual type it is, then you must know the type to begin with.
If there's something else that is missing from this question please elaborate and maybe there is a more appropriate answer than simply, "This doesn't make much sense."
Perhaps you have a set of different types, all of which implement a known interface?
For example if you have several different user controls and want to load one of them into a container, each one might implement IMyWobblyControl (a known interface) yet you might not know until runtime which of them to load, possibly from reading strings from some form of configuration file.
In that case, you'll need to use reflection to load the actual type from something like the full assembly name, then cast it into your known type to use it.
Of course, you need to make sure that your code handles invalid cast, assembly not found and any of the other exceptions that are likely to come along through something as wobbly as this...
This seems like a job for Int32.Parse(string). But to agree with the others it seems this is "unique" and one should probably think gloves.
Here's a specific example of the problem involving Azure SQL Federations...which splits data into separate db's according to a key range.
The key range types are:
SQL / .Net SQL type / CLR .Net
INT / SqlInt32 / Int32, Nullable
BIGINT / SqlInt64 / Int64, Nullable
UNIQUEIDENTIFIER / SqlGuid /Guid, Nullable
VARBINARY(n), max n 900 / SqlBytes, SqlBinary /Byte[]
Ideally, a C# function param could take either .Net SQL type or CLR .Net type but settling on just one category of type is fine.
Would an "object" type param be the way to go? And, is there a feasible way to identify the type and convert it accordingly?
The concept is something like:
public void fn(object obj, string fedName, string distName, bool filteringOn)
{
...figure out what type obj is to ensure it is one of the acceptable types...
string key = obj.toString();
return string.Format("USE FEDERATION {0} ({1}='{2}') WITH RESET, FILTERING = {3}", fedName, distName, key, (filteringOn ? "ON" : "OFF"));
}
Though the param value is cast to string, it will be recast/checked on the sql server side so validating it on the app side is desired.
After using:
Type type = Type.GetType(typename);
Try this extension method:
public static class ReflectionExtensions
{
public static T CreateInstance<T>(this Type source, params object[] objects)
where T : class
{
var cons = source.GetConstructor(objects.Select(x => x.GetType()).ToArray());
return cons == null ? null : (T)cons.Invoke(objects);
}
}
Hope this helps.

Categories