Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Generics into method

Tags:

c#

generics

I have a class:

public class ClassA<T>
{
  public T Value {get; set;}
  public string Description {get; set;}
}

ClassA can have a value of any type, however: I need to be able to set other properties of anything that is ClassA regardless of the type value. So I have a method:

public void DoWork(ClassA<object> source, ClassA<object> destination)
{
  destination.Description = source.Description;
}

However when I try to do this I get a runtime error saying that: cannot convert from ClassA<DateTime> to ClassA<object>

I thought that anything could be passed as an object... I've looked all over the web for something similar, maybe I'm just not getting the keywords right.

Anyone have any suggestions?

Thanks

like image 573
Captain Redbelly Avatar asked Dec 26 '22 13:12

Captain Redbelly


1 Answers

You won't be able to do that.

If you could pass a ClassA<int> into a method accepting a ClassA<object> wrapper then that method would be able to call wrapper.Value = "not an integer";. What should happen then? You've just set a string to an object that can only hold integers. Since the compiler knows it can't enforce what you could put it, it just doesn't let you pass the object in the first place.

As for the actual solution, two come to mind.

You could make your method generic, if that's an option:

public void DoWork<TSource, TDestination>(ClassA<TSource> source, ClassA<TDestination> destination)
{
  destination.Description = source.Description;
}

Or you could make a covariant interface:

public interface IWrapper<out T>
{
    T Value {get;}
    string Description {get;set;}
}

public class ClassA<T> : IWrapper<T>
{
    //...
}

public void DoWork(IWrapper<object> source, IWrapper<object> destination)
{
  destination.Description = source.Description;
}

For your DoWork method you don't even actually use the Value, so you could make the interface non-generic, non-covariant, and just remove Value. The advantage here is that you could use that interface to access the value properties of any number of ClassA objects that have a common base type.

like image 50
Servy Avatar answered Jan 15 '23 19:01

Servy