Khalid
Khalid

Reputation: 371

Problem with extension method with asp.net web form page code behind

i am creating an extension method to check null datarow with c#, i am trying to use the extension method in my asp.net web form code behind but giving me that the method IsEmpty doesnot in the current context here is the code i am trying

 public static class IsNullValidator
    {
        public static bool IsNullEquivalent( this object value)
        {
            return value == null
                   || value is DBNull
                   || string.IsNullOrWhiteSpace(value.ToString());
        }
        public static bool IsEmpty( this DataRow row)
        {
            return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
        }
    }

and i call it like this

DataRow[] row =getRowMethod();
if IsEmpty(row){"do some functionality"}

if i changed IsEmpty Signature by removing this keyword to below it works like this

   public static bool IsEmpty(  DataRow row)
            {
                return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
            }
   if IsEmpty(row[0]){"do some functionality"}

i need to work with this extension to check any datarow and in future to check any datatable and can i use the below method to check null datatable

 public static bool IsEmptyDatatable (DataTable dt)
    {
        return dt == null || dt.Rows.Cast<DataRow>().Where(r=>r.ItemArray[0]!=null).All(i => i.IsNullEquivalent());
    }

Upvotes: 1

Views: 457

Answers (2)

Khalid
Khalid

Reputation: 371

finally i ended up with the bellow solution ,thank you people ...all what you suggested were helpful

 public static bool IsNullEquivalent( this object value)
        {
            return value == null
                   || value is DBNull
                   || string.IsNullOrWhiteSpace(value.ToString());
        }
        public static bool IsEmptyDataRow(this  DataRow row)
        {
            return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
        }
        public static bool IsEmptyDatatable (this DataTable dt)
        {
            return dt == null || dt.Rows.Cast<DataRow>().All(i => i.IsEmptyDataRow());
        }

Upvotes: 1

Simply Ged
Simply Ged

Reputation: 8642

Extension methods are "extensions" of a type. In your case you are extending the DataRow class. For extension methods you need to have an instance of that class to call it e.g.:

DataRow[] row =getRowMethod();

if row.IsEmpty(){"do some functionality"}

In the example, the extension method is called on the instance row of the DataRow class.

If you think of the this keyword as saying "this method can be called on an instance of 'this' class" - which in your case is DataRow, that might help you to understand it.

Upvotes: 1

Related Questions