I am using the following code:
public static string ToJSONString(this object obj)
{
using (var stream = new MemoryStream())
{
var ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
But when the object is null I get the following:
System.NullReferenceException was unhandled by user code HResult=-2147467261 Message=Object reference not set to an instance of an object.
Is there a way I could catch this exception and return it to the calling program. Right now it gives me the above error and Visual Studio comes to a stop.
ArgumentNullExceptionin this case or - if you don't want an exception - returnnull(orString.Empty).ArgumentNullException- but it's still going to be an exception which indicates a bug, and shouldn't be caught... basically the caller shouldn't be doing that.object obj1 = null; string json = obj1.ToJSONString();wouldn't throw aNullReferenceException. An extension method is a static method, you don't need an instance.