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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -