.NET Generics constraints

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Aquarian
    New Member
    • Mar 2008
    • 1

    .NET Generics constraints

    I have a question in .NET Generics regarding the constraints.

    How would I prevent a value type from being used as the type parameter?

    say i have a generic class Foo

    class Foo<T> {

    }

    I want to prevent T from being a value type say only structs. Integral value types are ok. (int,float,doub le). what i want is the effect something like

    class Foo<T> where T not struct //instead of the T : struct
    {
    T()
    {
    //if type of T is a struct type throw exception.
    }
    }
    I know there isnt a direct way, but i am looking at something like a check at ctor and throw an exception if the type is determined to be a struct type.
  • Semajthewise
    New Member
    • Nov 2007
    • 38

    #2
    Originally posted by Aquarian
    I have a question in .NET Generics regarding the constraints.

    How would I prevent a value type from being used as the type parameter?

    say i have a generic class Foo

    class Foo<T> {

    }

    I want to prevent T from being a value type say only structs. Integral value types are ok. (int,float,doub le). what i want is the effect something like

    class Foo<T> where T not struct //instead of the T : struct
    {
    T()
    {
    //if type of T is a struct type throw exception.
    }
    }
    I know there isnt a direct way, but i am looking at something like a check at ctor and throw an exception if the type is determined to be a struct type.
    Try something like this to check if "T" is a struct
    [code=vbnet]
    Try
    If T Is GetType(StructF ormat) Then

    End If ' placed at the beginning of your class

    catch ex as Exception ' placed at the end of your class
    End Try

    [/code]
    I believe it may do what you want.
    it should check as it goes along and if T becomes a struct at any time the exception should be thrown.
    but I am no expert.
    Hope it works or gives you an idea.
    Good luck

    Comment

    Working...