-4

I moved from Java to C# and I am automating webservices in C#. There is a piece of code which is calling below method for converting the XML document to String

XmlDocument document = new XmlDocument();
document.Load(filePath + fileName);            
var xml = document.ToXml();

public static string ToXml<T>(this T toSerialize) where T : class

Can someone explain me what exactly the above method is doing, i understand the return type is String but what is this piece of code meant ToXml<T>(this T toSerialize) where T : class

Can someone also explain me what is meant by "generic"?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
rackhwan
  • 265
  • 5
  • 14

2 Answers2

3

It's an extension method:

public static string ToXml<T>(thisT toSerialize) where T : class

And a generic one at that, constrained to reference types:

public static string ToXml<T>(thisTtoSerialize)where T : class

This means that you can call the method on any reference type:

var foo = new YourClass
{
    Bar = "Baz"
};
string xml = foo.ToXml<YourClass>();

And because the generic parameter type is used as a reference type, you can let it be inferred, omitting the generic argument:

string xml = foo.ToXml();

You could also just use File.ReadAllText() to load a text file into a string.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
2
public static string ToXml<T>(this T toSerialize) where T : class

Let me break it down for you

<T>                  // This is the templated or generic type name.
where T : class      // This syntax restricts the generic type to be a class (as opposed to a struct)
this T toSerialize)  // The "this" keyword here can be ignored as it has nothing to do with the generics. It just tells that the caller can call this method like toSerialize.ToXml() instead of ContainingClass.ToXml(toSerialize)

In C#, you may or may not have to explicitly provide the generic type information at the call site, depending on the situation. In your case, it will be resolved without need for explicit specification

An explicitly specified call would like like

var xml = document.ToXml<XmlDocument>();

As you already have realized the var keyword is used instead of explicitly specifying string, since the compiler can infer the type very easily from the context.

You can read up on Generics and the contraints. Also, you can read up on Extension Methods. This should get you a solid understanding of the syntactical elements involved

Vikhram
  • 4,294
  • 1
  • 20
  • 32