Generic class to handle nullable for primitive types in .NET  C#

countrymeister
countrymeister used Ask the Experts™
on
I want to create a generic class which when invoked will handle the return of nulls for primitive types such as bool, int

I want to have  a where clause which will only restrict primitive types, any code sample willbe great
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
you can do something like this:

List<bool?> myGenericNullableBoolList = new List<bool?>();
myGenericNullableBoolList.Add(null);
myGenericNullableBoolList.Add(true);
myGenericNullableBoolList.Add(false);
foreach(bool? myBool in myGenericNullableBoolList)
            if(myBool.HasValue)
                   MessageBox.Show(myBool.Value.ToString());
            else
                  MessageBox.Show("No Value Present");

Author

Commented:
Omego2K:

I am looking for something across all primitive types, can I add some where clause in my generic class
Not sure if this is possible

Example Class<T?> where T: Nullable

Commented:
If you are looking to declare a class then you cannot do this as you cannot restraint based on primitive types as they are sealed

best thing you can do is throw an exception:

public class MyNullable<T>
{
         public MyNullable(){ if(!(typeof(T) is int){ throw new ApplicationException("Some Message"); }}

}

Author

Commented:
Omego2K:

I ended adding return values of Nullable to my methods and fixed my issue.

But you are correct that I cannot apply where clause with primitive types

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial