I have a class like this:
public static class Extras
{
static Extras()
{
}
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
It’s used to serialize an object, and it’s in its own class library.
When I reference the class in my main MVC project I get the following message from the compiler:
Type'ReablementExtras.Extras' has no constructors.
Please can someone tell me tiny little mind why?
Thanks.
A static class can’t be instantiated. You can only call the methods or properties via the class name:
This kind of writing is called
Extension Method. You can also call the method as if it was a class member of any type:if you don’t see the
SerializeObjectin the intellisense list you need to add ausingstatement, which is in your case:The reason you see the “no constructor” error is because this constructor is static. Static constructors can’t be invoked directly but the framework invokes them just before you access the first method or property of this class.
Static constructors also cannot have an access modifier (public, private etc…) and cannot have any parameters.