Why can XmlDictionaryWriter.CreateBinaryWriter return an instance of an abstract class? - abstract

XmlDictionaryWriter is an abstract class.
Why then does it have a constructor?
Why can its method "CreateBinaryWriter" return an instance of this abstract class?
I understand CreateBinaryWriter passes a stream to which the instance of this "abstract" class writes.
It makes me wonder how abstract "abstract" really is...
By all that has been elaborated on the keyword abstract this does not fit the picture.
Code:
MemoryStream WriteName(Name name)
{
var ms = new MemoryStream();
var binary = XmlDictionaryWriter.CreateBinaryWriter(ms);
var ser = new DataContractSerializer(typeof(FullName));
ser.WriteObject(binary, name);
return ms;
}
Could s.o. explain?
thx

I can't see full XmlDictionaryWriter hierarchy, but I think XmlDictionaryWriter.CreateBinary() is not a contructor but a static method; what can we see is an implementation of factory method pattern using static methods.
Is possible to call an abstract class' static method because a static method doesn't need an object instance (you can read more at Difference between Static methods and Instance methods)

Related

Can I use a no-arg constructor with Hazelcast Portable?

The Hazelcast documentation on their Portable serialization mechanism says that you are not forced to use a no-arg constructor.
https://hazelcast.org/mastering-hazelcast/#serialization-start
But their example code shows fields being set directly.
#Override
public void readPortable(PortableReader reader) throws IOException {
System.out.println("Deserialize");
this.name = reader.readUTF("name");
}
and the factory used to create instances of the class being deserialized is using a no-arg constructor.
#Override
public Portable create(int classId) {
switch (classId) {
case PERSON_CLASS_ID:
return new Person();
}
return null;
}
Am I right in assuming that you are not forced to use a no-arg constructor but you can't use it to set field values when deserializing? How would you handle enforcing invariants such as never-null fields and how would you deserialize a subclass without making the fields in the superclass protected?
While deserializing you can't maintain invariants since the object is being reconstructed; so some fields are just not set. There is no point resisting this.
And you are not forced to have a no-arg constructor. As long as the factory can create an instance, HZ doesn't care how you create it.

Code restricting: Create of more than one object in private constructor in C#

I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.

How DbContext initializes automatic DbSet<T> properties?

Consider the following class:
class MyContext : DbContext
{
public DbSet<Order> Orders { get; set; }
}
and instantiating a new object:
var mycontext = new MyContext();
Why mycontext.Orders is not null? When it was initialized? Who has initialized it? I'm really confused because the base class (DbConetxt) cannot access the derived class properties so it is not possible that the automatic property was initialized in the base object.
From looking at the reflected code, when the DbContext (the base class) is constructed it makes a call to the DbSetDiscoveryService (an internal clasS) - which essentially uses reflection to find all properties on the DbContext, and then initializes those that need initializing.
So in short - using reflection in the constructor.

initializing derived class member variables using base class reference object

I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref( var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method( )
{
_ref.der_e = 444; // won't compile
}
}
What is the correct way to initialize der_e ? What is the advantages of having a reference of base class and using an object derived class for _ref ? Just the fact that using a base class reference can hold multiple derived class objects ? If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ). What if I want to initialize _ref.der_e later in a method ? I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e = 444) but this look doesn't seem to the best practice. What is the idea of having such a structure and what is the correct of initializing a member of a derived class object after it has been constructed ?
Those are too many questions in a single post.
What is the correct way to initialize der_e ?
For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class.
What is the advantages of having a reference of base class and using
an object derived class for _ref ?
Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation.
If that's the case, should all the member variables of derived class
be initialized during construction itself (like this: _ref = new
Derived (a,b,c,d) )
There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creation of the object and the values are known before hand during construction of the object then they should be initialized during construction.
Again if there are various scenarios like sometimes values are known and sometimes not then there can be Overloaded Constructors, which take different arguments.
What if I want to initialize _ref.der_e later in a method ?
That is perfectly fine, it depends on what you are trying to achieve. The question is not a concrete one but an abstract one in which it is difficult to comment on what you are trying to achieve.
I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e =
444) but this look doesn't seem to the best practice.
I am sharing some Java code which is similar to C# as I am from Java background
//This class knows about Base and nothing about the Derived class
class UserOfBase{
Base ref;
//Constructor of UserOfBase gets passed an instance of Base
public UserOfBase(Base bInstance){
this.ref = bInstance;
}
//Now this class should not cast it into Derived class as that would not be a polymorphic behavior. In that case you have got your design wrong.
public void someMethod(){
Derived derivedRef = (Derived)ref; //This should not happen here
}
}
I am sharing some references which would help you with this, as I think the answer can be very long to explain.
Factory Pattern
Dependency Injection
Head First Design Patterns
Posts on SO regarding polymorphism
You can create a constructor in your derived class and map the objects or create an extension method like this:
public static class Extensions
{
public static void FillPropertiesFromBaseClass<T1, T2>(this T2 drivedClass, T1 baseClass) where T2 : T1
{
//Get the list of properties available in base class
System.Reflection.PropertyInfo[] properties = typeof(T1).GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
System.Reflection.PropertyInfo isPresent = drivedClass.GetType().GetProperty(property.Name);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
object value = baseClass.GetType().GetProperty(property.Name).GetValue(baseClass, null);
drivedClass.GetType().GetProperty(property.Name).SetValue(drivedClass, value, null);
}
});
}
}
for example when you have to class like this:
public class Fruit {
public float Sugar { get; set; }
public int Size { get; set; }
}
public class Apple : Fruit {
public int NumberOfWorms { get; set; }
}
you can initialize derived class by this code:
//constructor
public Apple(Fruit fruit)
{
this.FillPropertiesFromBaseClass(fruit);
}

Using reflection how to find a class in an assembly which implements a generic base class and create its instance

I've a base presenter class:
public abstract class PresenterBase<T> where T : IView
{
//Some code
}
A concrete presenter class that implements this base:
public class RegistrationPresenter : PresenterBase<IRegistration>
{
//Some Code
}
A concrete presenter factory to return the instance of presenter which depends on a specific interface contract:
public class ProductPresenterFactory : PresenterFactoryBase
{
// Some code
public override PresenterBase<IView> GetPresenter(IView view, string name = "")
{
if (view == null && string.IsNullOrEmpty(name))
throw new ArgumentNullException();
return presenter;
}
}
I need to implement the GetPresenter method. The user will put the interface contract, for example of type IRegistration in the above case. This method should figure out the class that implements PresenterBase<IRegistration> and return an instance.
I did not write this with a compiler; I might have made a few mistakes.
You'll first need to get the type of the presenterbase, then we'll scour the assemble for the implementation, then call it's constructor. I'll make some assumptions as written in the code.
var genericType = typeof (PresenterBase<>).MakeGenericType(new[] { view.GetType() });
var allTypes = GetType().Assembly.GetTypes(); // I assume the class is in the same assembly.
var typeToImplement = allTypes.Single(t => t.IsSubclassOf(genericType)); // I assume there is only one implementation for the given type
var constructorToCall = typeToImplement.GetConstructors().First(); // I assume there is one constructor
var presenter = constructorToCall.Invoke(new object[0]); // I assume there is no parameter

Resources