Skip to main content
gamedev.net
🔒 Locked

C# Generics

Started by SiS-Shadowman 3 replies 800+ views
Original Post
SiS-Shadowman
SiS-Shadowman
With c# generics, I know it is possible to place constraints on the type argument, for example that it must implement a certain interface or inherit a certain class. Is the same thing possible in a static context? Can I require that the type that is passed offers a static method or property?

I know that this is possible with reflection, but maybe there's another way for this kind of problem.

I'm probably still used to c++ template, which work in a completely different manner.
Nypyren
Nypyren
The only way you can require a method is by constraining using an interface. So, if you don't have source for a type you want to pass to your code, you'd have to apply a wrapper:

public class SomethingYouDontHaveSourceCodeFor{  public void Foo() {...}}public interface IFooMethod{  void Foo();}public class Wrapper : IFooMethod{  SomethingYouDontHaveSourceCodeFor obj;  // obvious constructor    void IFooMethod.Foo() { obj.Foo(); }}public static class Test{  public static void CallFoo<T>(T blarg) where T : IFooMethod  {    blarg.Foo();  }  public static void CallFoo2(IFooMethod blarg)  {    blarg.Foo();  }  public static void Main()  {    SomethingYouDontHaveSourceCodeFor c = new ... (not typing that out again)    Wrapper w = new Wrapper(c);        CallFoo(w);    // or    CallFoo2(w);  }}
Nypyren
Nypyren
You could throw caution to the wind and use dynamic but then static-type-nazis like me would seriously frown at you.

(edit) RE: Gage64: I would still have had to type it out at least once even WITH var :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.