Reputation: 2474
I have a few Types
which all have the same "meta data" properties. I want to have a method where I can pass an object, of any Type
, as an argument to update its meta data.
I can use a dynamic
argument in the method, something like this:
private void UpdateMeta(dynamic obj)
{
obj.meta1 = DateTime.Now;
obj.meta2 = "acb";
obj.meta3 = 123;
obj.meta4 = "foo";
}
Type1 objtype1 = new Type1();
Type2 objtype2 = new Type2();
Type3 objtype3 = new Type3();
UpdateMeta(objtype1);
UpdateMeta(objtype2);
UpdateMeta(objtype3);
But what about type safe generics, what is the exact syntax? Here is what I have so far:
private void UpdateMeta<T>(ref T obj)
{
obj.meta1 = DateTime.Now;
obj.meta2 = "acb";
obj.meta3 = 123;
obj.meta4 = "foo";
}
Type1 objtype1 = new Type1();
Type2 objtype2 = new Type2();
Type3 objtype3 = new Type3();
UpdateMeta<Type1>(objtype1);
UpdateMeta<Type2>(objtype2);
UpdateMeta<Type3>(objtype3);
I've looked up examples and documentation but it's mostly about generic classes. I can't seem to get the syntax right
Upvotes: 1
Views: 260
Reputation: 101681
You need a common base class or interface.then just add a constraint to your generic method:
public interface ICommonInterface
{
// declare your properties here
// and don't forget to implement this interface in your classes
}
private void UpdateMeta<T>(T obj)
where T : ICommonInterface
{
obj.meta1 = DateTime.Now;
obj.meta2 = "acb";
obj.meta3 = 123;
obj.meta4 = "foo";
}
As mentioned in the comments, you don't even need to use generics in this case because you are only updating values of some properties.You can just have a method that takes a parameter of type common interface.You can do that changing dynamic with a common interface or base class in your first code snippet and you gain the type-safety.
Upvotes: 4