Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic way to check null or empty for any type like int, string, double

Tags:

c#

generics

I am trying t get this working but somehow its going out of my hand... I want to be able to check null or empty to whatever type i assigned.

EX:

int i =0;
string mystring = "";

var reult  = CheckNullOrEmpty(10) // passing int
var result 1  = CheckNullOrEmpty(mystring) // passing string 

 public bool CheckNullOrEmpty<T>(T value)
 {
    // check for null or empty for strings
    // check for null i.e. 0 for int 

 }

can someone help me with this.. I am trying to understand how generics works for this simple method.

like image 425
patel.milanb Avatar asked May 15 '13 09:05

patel.milanb


People also ask

How check double value is null or not in C#?

IsNaN() Method in C# In C#, Double. IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN).

How do you check if all properties of an object are null or empty in Java 8?

Properties isEmpty() method in Java with Examples The isEmpty() method of Properties class is used to check if this Properties object is empty or not. Returns: This method returns a boolean value stating if this Properties object is empty or not.

Is null or empty in typescript?

Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

How check variable is empty or not in Javascript?

Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.


2 Answers

public static bool CheckNullOrEmpty<T>(T value)
{
     if (typeof(T) == typeof(string))
        return string.IsNullOrEmpty(value as string);

     return value == null || value.Equals(default(T));
}

How to use:

class Stub { }

bool f1 = CheckNullOrEmpty(""); //true
bool f2 = CheckNullOrEmpty<string>(null); //true
bool f3 = CheckNullOrEmpty(0); //true
bool f4 = CheckNullOrEmpty<Stub>(null);  //true
like image 114
cuongle Avatar answered Oct 01 '22 05:10

cuongle


You can check against default(T);

 public bool CheckNullOrEmpty<T>(T value)
 {
      return value == default(T);
 }

For more informations: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

like image 45
nein. Avatar answered Oct 01 '22 05:10

nein.