Why would you not be able to use
out
or
ref
when using
Generics
?
See the following example.
class Program
{
static void Main(string[] args)
{
int i = 10;
GenericExample<int> ge = new GenericExample<int>();
Console.WriteLine("The value of i is " + i.ToString());
ge.SetSomeValue(ref i);
Console.WriteLine("The value of i is " + i.ToString());
Console.ReadKey();
}
}
public class GenericExample<TResult>
{
public bool SetSomeValue(ref TResult value)
{
value = Activator.CreateInstance<TResult>();
return true;
}
}
When running this code in a console application you will see that
i
is 10 before executing the function and 0 after executing it. You can set
i
as the value of whatever
Property
you want.
However, why do you need to return a
bool
to indicate success? Why not simply return an instance of
TResult
and throw an
Exception
if something went wrong (it reduces the amount of
if-blocks
and allows for proper error handling)?
If you really wanted to set a
Property
(that is, invoke the set method on a
Property
and passing the value that was somehow calculated in your method) you could use
Reflection
, but I don't recommend it. Here is how you would do it.
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.SomeProperty = 24;
GenericExample<int> ge = new GenericExample<int>();
Console.WriteLine("The value of SomeProperty is " + p.SomeProperty.ToString());
ge.SetProperty(p, "SomeProperty");
Console.WriteLine("The value of SomeProperty is " + p.SomeProperty.ToString());
Console.ReadKey();
}
}
public class Person { public int SomeProperty {get; set;} }
public class GenericExample<TRresult>
{
public bool SetProperty(object obj, string propertyName)
{
System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(propertyName);
prop.GetSetMethod().Invoke(obj, new object[] {Activator.CreateInstance<TResult>()});
return true;
}
}
You can see the downsides to this. If you would change the name of
SomeProperty
or misspell it you wouldn't get design time support for the error.