Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it that the abstract class XmlWriter can be instantiated using XmlWriter.Create(...?

Tags:

c#

.net

Just looking to clarify my understanding of the workings of the XmlWriter and abstract classes in general.

My thinking is (was) that an abstract class can not be instantiated, although it can contain base methods that can be used by an inheriting class.

So, while investigating XmlWriter, I find that to instantiate the XmlWriter, you call XmlWriter.Create(.... , which returns an instance of... XmlWriter, which can then be used:

FileStream fs = new FileStream("XML.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

XmlSerializer xmlSlr = new XmlSerializer(typeof(TestClass));

xmlSlr.Serialize(fs, tsIn);

This clearly works, as tested. Can anyone help me understand what is going on here. As far as I can see there is or should be no 'instance' to work with here??

like image 487
gb2d Avatar asked May 21 '10 11:05

gb2d


People also ask

How to Create XmlWriter in c#?

Creates a new XmlWriter instance using the stream and XmlWriterSettings object. Creates a new XmlWriter instance using the specified XmlWriter and XmlWriterSettings objects. Creates a new XmlWriter instance using the specified StringBuilder. Creates a new XmlWriter instance using the specified filename.

Can we create an instance of abstract class C#?

An abstract class cannot be instantiated. An abstract class may contain abstract methods and accessors. It is not possible to modify an abstract class with the sealed modifier because the two modifiers have opposite meanings.


2 Answers

You can't create an instance using new, but Create as it is used here is what is called a static factory method; it is NOT a constructor. You will find that in fact, the object returned by Create does not belong to abstract class XmlWriter, but some other concrete subclass.

See also

  • Wikipedia/Factory method pattern
like image 182
polygenelubricants Avatar answered Sep 21 '22 16:09

polygenelubricants


There's nothing abstract about the object you get back. There are 13 classes inside the .NET framework that implement XmlWriter. They are all internal, you could only see their names if you'd peek at the source code with Reflector.

Not having to know the names of those 13 classes yourself is very valuable both to you and Microsoft. To you because you don't have to learn the details of picking the right one. To Microsoft because they can completely change the implementation, even the name, of those classes and your code would never notice.

This is called the Factory Pattern.

like image 40
Hans Passant Avatar answered Sep 19 '22 16:09

Hans Passant