c# - Generic class accepts primitive type and string -
how create generic type accepts type of integer, long , string.
i know can restrict type single class or implementing interface below code
public class mygenericclass<t> t:integer{ }
or handle int,long not string
public class mygenericclass<t> t:struct
is possible create generic accepts type of integer, long , string?
you potentially not have constraints in class declaration, type-checking in static constructor:
public class mygenericclass<t> { static mygenericclass() // called once each type of t { if(typeof(t) != typeof(string) && typeof(t) != typeof(int) && typeof(t) != typeof(long)) throw new exception("invalid type specified"); } // eo ctor } // eo class mygenericclass<t>
edit:
as matthew watson points out above, real answer "you can't , shouldn't". if interviewer believes that incorrect, don't want work there anyway ;)
Comments
Post a Comment