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"?
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.
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
Related
I was learning C# and found that there is some type of value defined by
var json = new {name="App", age=20};
Although this seems to be similar to the JSON type. But when I tried to use the GetType method, I got <>f__AnonymousType0`2[System.String,System.Int32]
Can anyone help me in this please?
In case you want the full code
using System;
public class Program
{
public static void Main()
{
var c = new { name="App", age=22 };
Console.WriteLine(c.GetType());
Console.WriteLine(c);;
}
}
It's called Anonymous Type and it has no relation to JSON.
You can read about it FROM MSDN
Anonymous types provide a convenient way to encapsulate a set of
read-only properties into a single object without having to explicitly
define a type first. The type name is generated by the compiler and is
not available at the source code level. The type of each property is
inferred by the compiler.
In object-oriented programming, everything is supposed to be an object. Starting from this postula, is it possible to add methods and fields to a literal object, such as a number, a string, a Boolean value or a character?
I noticed that in C#, we can use some methods and fields of the "Integer" class from a mathematical expression:
var a = (2 + 2).ToString();
I imagine that it is more syntactic sugar to access the "Integer" class and a method actually related to the mathematical expression (and / or its value).
But is it possible in C# to define one of the methods and fields to a literal object alone? Such as these examples:
"Hello, world!".print();
var foo = 9.increment();
This would probably be useless, but the language being object-oriented, this should be feasible. If this is not possible in C#, how could we do this with the object-oriented paradigm?
Sure, you can implement an extension method and have the desired syntax (however, Int32 class will not be changed):
public static class IntExtensions {
public static int increment(this int value) {
return value + 1;
}
}
...
// Syntax sugar: the actual call is "int foo = IntExtensions.increment(9);"
var foo = 9.increment();
In the current C# version (7.2) we can't add extension properties, extension events etc. These options can appear in C# 8.0 (Extension everything, https://msdn.microsoft.com/en-us/magazine/mt829270.aspx):
You don't add methods to a given instance of an object, you add methods to a type. Additionally, the language doesn't allow you to define what methods a string (or other type of) literal has, it defines what methods all strings have, of which string literals act just like any non-literal strings, and have exactly the same methods.
Note that (2 + 2) is not an instance of the "Integer" class, it will resolve to an instance of the System.Int32 struct. The difference isn't relevant to this behavior, but it's relevant to lots of others.
"Hello, world!".print();
This string is an instance of the String Class in C# which inherits from the Object class. So you have to create the print() method in the String Class in order to make this work.
You can use extension methods to achieve this, which must be static methods defined in a static class. In you example above, you could do the following:
public static class Extensions
{
public static int increment(this int num)
{
return ++num;
}
}
I'm trying to generate code for series of generic classes using T4.
I want to know how to get full class name using reflection?
public class Foo<TFirst, TSecond> {}
var type = typeof(Foo<,>);
var name = type.FullName; // returns "Foo`2"
what I want is full name with actual generic parameter names that I've written
"Foo<TFirst, TSecond>"
Note that they are not known type, as I said I'm generating code using T4, so I want to have exact naming to use it for code generations, as an example, inside generic methods.
I tried this answers but they require to pass known type which is not what I want.
You can access the type parameter names by reflection using Type.GetGenericArguments:
using System;
public class Foo<TFirst, TSecond> {}
class Test
{
static void Main()
{
var type = typeof(Foo<,>);
Console.WriteLine($"Full name: {type.FullName}");
Console.WriteLine("Type argument names:");
foreach (var arg in type.GetGenericArguments())
{
Console.WriteLine($" {arg.Name}");
}
}
}
Note that that's giving the type parameter names because you've used the generic type definition; if you used var type = typeof(Foo<string, int>); you'd get String and Int32 listed (as well as a longer type.FullName.)
I haven't written any T4 myself, so I don't know whether this is any use to you - in order to get to Foo<TFirst, TSecond> you'd need to write a bit of string manipulation logic. However, this is the only way I know of to get at the type arguments/parameters.
Why .NET does not provide implicit or explicit conversion converting from string to the defined type and from the defined type to the string?
Example:
public class MyClass
{
public int Id;
public MyClass()
{
}
}
I can do:
var myClass = new MyClass() {Id=1};
string myClassString = myClass.ToString();
WHY I CANNOT DO?:
var myClassConverted = (MyClass) myClassString ;
Is there any serialization pattern exist can to that?
.ToString() is just a method , it can return any String value, this does not convert a class to a String.
We already have some questions about converting class to text:
Create an instance of a class from a string
C# Convert dynamic string to existing Class
Convert class to string to send via email
Converting Class to XML to string
Personally I use more the XML serialization approach, is very easy to serialize and deserialize and works very well with external services, like REST or SOAP.
ToString() is a method defined on the Object class which returns a new string instance and is not a type conversion.
There is no conversion that can be used to cast a String to your class but you can define your own custom conversion operator.
public class MyClass
{
public int Id;
public MyClass()
{
}
public static explicit operator MyClass(string s)
{
MyClass temp = new MyClass() { Id = Int32.Parse(s) };
// you should handle exceptions when string is not convertible to int
return temp;
}
}
You can then use your conversion:
MyClass c = (MyClass)("1");
From MSDN:
C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. Conversions are defined like operators and are named for the type to which they convert. Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type.
Conversion operators have the following properties:
Conversions declared as implicit occur automatically when it is required.
Conversions declared as explicit require a cast to be called.
All conversions must be declared as static.
You can find more on MSDN.
Quote from msdn Object.ToString Method :
The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.
using System;
public class Example
{
public static void Main()
{
Object obj = new Object();
Console.WriteLine(obj.ToString());
}
}
// The example displays the following output:
// System.Object
.ToString() does not contain any unique information of your current object so you can not reconstruct the object from this string.
If you want to serialize or deserialize your object take a look here:
How to save/restore serializable object to/from file?
You cant really compare ToString() with a "Explicit cast". Both are different indeed.
Plausible comparison should be like this. You should be trying to cast "MyClass to string", that would fail.
Neither Cast from MyClass to string nor string to MyClass` is allowed.*[1]
var myClass = new MyClass() {Id=1};
string myClassString = (string)myClass;//Note this also will fails since no conversion beween `MyClass` to `string`
When you compare ToString method ideally you should be comparing with FromString method unfortunately no such thing.
Back to your question
var myClassConverted = (MyClass)myClassString;
WHY I CANNOT DO?:
Because there is no implicit or explicit conversion between string to MyClass.
[1]To make it work you may use implicit or explicit operators though.
Can anyone else explain this, (beginners approach). Thanks..
Extension Methods are just static methods in static classes that behaves like they were defined in other class.
In the first parameter before the type goes the keyword this wich indicates that is an extension method.
Example:
public static class Extensions
{
public static object ExtensionMethodForStrings( this string s, object otherParameter)
{
//....
return //whatever you want to return or not
}
}
This is an extension method on System.String that takes two parameters:
- string s : This is the instance variable
- object otherParameter: You can have as many as you want including none
You can call this method in two ways:
Static way:
string s = "Your string";
object o = new object(); // or whatever you want
object result = Extensions.ExtensionMethodForStrings(s,o);
Extension Method way
string s = "Your string";
object o = new object(); // or whatever you want
object result = s.ExtensionMethodForStrings(o);
In the second case it works as if the type string has an instance method called ExtensionMethodForStrings. Actually for the compiler the are equivalent.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
The C# article on Extension Methods.
An extension method is a static method in a static class whose first parameter is preceded by the keyword this.
The C# compiler has some syntactic sugar that can convert a call of x.Foo(bar) to SomeExtension.Foo(x, bar). This is used extensively by LINQ (Take, Skip, Where, Select, etc.) but you can also write your own extension methods if you wish.
This question includes lots of examples of useful extension methods:
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)
An extension method is a method that behaves (somewhat) like it is a member of a class, but it is not a member of that class. It can be called on members of that class, but has no reference to the internals of the class.
Extension methods are static methods, and must be members of a static class.
public static class StringExtensions
{
public static string HtmlEncode(this string dataString)
{
return HttpServerUtility.HtmlEncode(dataString);
}
}
The keyword "this" prior to the first parameter type identifies this as an extension method, and the class it extends.
It would be used this way:
string foo = "bar";
string myOutput = foo.HtmlEncode();