-
Notifications
You must be signed in to change notification settings - Fork 2
Object extensions
halcharger edited this page Apr 8, 2014
·
6 revisions
#####ObjectExtensions.Clone
A simple extension method to make a deep copy of an objects public properties. All basic .NET data types are supported as well as structs and complex types The deep copy also supports arrays and anything inheriting from IList.
var source = new ComplexObject();
var clone = source.Clone();
ReferenceEquals(source, clone) == false
clone
will be a deep copy of source
#####ObjectExtensions.GetValueForProperty
When working with reflection it can often become tedious to retrieve and set the values of properties dynamically.
Given:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
Object user = new User { Id = 2, Name = "John" };
Instead of:
var propertyInfo = user.GetType().GetProperty("Id");
if (propertyInfo.GetValue(user) == 2)
{
//do something
}
We can write:
if (user.GetValueForProperty("Id") == 2)
{
//do something
}
#####ObjectExtensions.SetValueForProperty
When working with reflection it can often become tedious to retrieve and set the values of properties dynamically.
Given:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
Object user = new User { Id = 2, Name = "John" };
Instead of:
var propertyInfo = user.GetType().GetProperty("Id");
propertyInfo.SetValue(user, 3)
We can write:
user.SetValueForProperty("Id", 3)
#####ObjectExtensions.ToNullSafeString
Given:
public class User
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
User user = null;
Instead of:
var username = user == null ? string.Empty : user;
We can write:
var username = user.ToNullSafeString();
username == ""
Or we could write:
var username = user.ToNullSafeString("null");
username == "null"