System.Object Extension Methods

CallMethodByName(string methodName, params object[] args)

Summary: Executes the method on an object and returns the result.
C# Example:
var result = obj.CallMethodByName("ToString");

var result = obj.CallMethodByName("SomeMethod", firstParamValue, secondParamValue);

CallMethodByName<T>(string methodName, params object[] args)

Summary: Executes the method on an object and returns the result case as the specified type.
C# Example:
var result = obj.CallMethodByName<string>("ToString");

IsType(Type type)

Summary: Returns a boolean value indicating whether a variable is of the indicated Type.
C# Example:
var obj = "";
var type = typeof(string);

if (obj.IsType(type)) {
    // do something
}

IsArray(object obj)

Summary: Returns a boolean value indicating whether a variable points to a System.Array.
C# Example:
var obj = new string[0];

if (obj.IsArray()) {
    // do something
}

IsDate(object obj)

Summary: Returns a boolean value indicating whether a variable points to a DateTime object.
C# Example:
var obj = DateTime.Now;

if (obj.IsDate()) {
    // do something
}

IsDBNull(object obj)

Summary: Returns a boolean value indicating whether an expression evaluates to the DBNull class.
C# Example:
var obj = DBNull.Value;

if (obj.IsDBNull()) {
    // do something
}

IsNull<T>(T obj)

Summary: Returns a boolean value indicating whether an expression evaluates to be NULL.
C# Example:
var obj = null;

if (obj.IsNull()) {
    // do something
}

GetAttribute<AttributeType>()

Summary: Returns the first Attribute tied to the Object of the Specified Generic Type.
C# Example:
var attr = obj.GetAttribute<DescriptionAttribute>();

GetAttributes<AttributeType>()

Summary: Returns all Attributes tied to the Object of the Specified Generic Type.
C# Example:
var attr = obj.GetAttributes<DescriptionAttribute>();

ToDictionary()

Summary: Returns a Dictionary containing Key/Value pairs that match the objects properties and their values.
C# Example:
var person = new {
    FirstName = "John",
    LastName = "Doe",
    Age = 64
};

var dict = person.ToDictionary();
// dict["FirstName"] will equal "John"
// dict["LastName"] will equal "Doe"
// dict["Age"] will equal 64

CastAs<T>(T targetType)

Summary: Allows you to easily pass an Anonymous type from one function to another
C# Example:
void mainMethod()
{
    var a = new {
        FirstName = "Chris",
        Age = 30
    }
    passToMethod(a);
}

void passToMethod(Object obj)
{
    var a = new {
        FirstName = string.Empty,
        Age = 0
    };

    a = obj.CastAs(a);

    var firstname = a.FirstName; // will be "Chris"
    var age = a.Age; // will be 30
}

Last edited May 4, 2012 at 2:09 PM by crpietschmann, version 12

Comments

No comments yet.