C# sample syntax question - c#

Please, help me with to understand this piece of code:
protected Customer()
{
}
in the following class (Model class from sample WPF MVVM app):
public class Customer : IDataErrorInfo
{
#region Creation
public static Customer CreateNewCustomer()
{
return new Customer();
}
public static Customer CreateCustomer(
double totalSales,
string firstName,
string lastName,
bool isCompany,
string email)
{
return new Customer
{
TotalSales = totalSales,
FirstName = firstName,
LastName = lastName,
IsCompany = isCompany,
Email = email
};
}
protected Customer() // it is what I asked about
{
}
#endregion // Creation
......
}

protected Customer() { } is a constructor, a special method that automatically gets called when you instantiate an object from a class. When you type Customer c = new Customer(), the constructor is allowed to initialize that instance after the run-time has allocated and reset memory for it. The protected keyword means that only code inside the class Customer or of its descendants are allowed to instantiate said class using that specific constructor.

The piece of code you point at is a constructor. It is a method that (potentially) gets automatically invoked whenever an instance of your class is created at runtime.
In this case, it is marked with the protected keyword. This means that only the owner class plus any derived classes (i.e. classes that inherit from it) have access to it.
By looking at your code, the two versions of the CreateNewCustomer() static method in your class create instances of the class, invoking the constuctor. By making the constructor protected, the code guarantees that the class retains exclusive control over instantiation; this means that no other code outside the class (or its descendant classes) can create instances of this class.

The constructor is protected so that only the static creation methods can actually instantiate the class.

This means that the constructor for your class has "protected" access, meaning that only members of this class or subclasses can call it. Practically, this means that either a static method is being used to create an instance of this class, or that another constructor (possibly in a derived class) is delegating to this constructor.

Using the protected keyword on the constructor only allows instantiation of the Customer object inside itself (like the static factory methods) and inside any class that derives from Customer.

Related

Inheritance - Can't access base class data member in derived class

One doubt in inheritance, I have two class named A and B.
A is Base Class and B is Derived Class.
B Class inheriting two data members and two member functions of A Class.
In derived class, accessing the static data member is Working but
accessing the non static data member gives error. This same case is
also for Member Functions. I can't access non static member function.
If i access either static or non static variable | function inside any of derived class function it working fine.
Why i can't access directly in a class. Why its not showing error when i access inside of any derived class function. Any one please clarify my doubts.
class A
{
protected string msg1;
protected static string msg2;
protected string alert1() {
return "Welcome";
}
protected static string alert2()
{
return "Welcome All";
}
}
class B : A {
string copyMsg1 = msg1;
string copyMsg2 = msg2;
string getMsg1 = alert1();
string getMsg2 = alert2();
void display() {
msg1 = "";
msg2 = "";
alert2();
}
}
This line is illegal:
string getMsg1 = alert1();
Because it is equivalent to
string getMsg1 = this.alert1();
and accessing this in a field initializer is illegal. Why? Because field initializers run before either the derived class constructor or the base class constructor, and therefore you could be calling a method that depends on the constructor having already run.
The correct solution is to put your initializations into the constructor:
class B : A {
string copyMsg1;
string copyMsg2;
string getMsg1;
string getMsg2;
public B()
{
this.copyMsg1 = this.msg1;
this.copyMsg2 = A.msg2;
this.getMsg1 = this.alert1();
this.getMsg2 = A.alert2();
}
The body of the constructor runs after the field initializers of the derived class, the field initializers of the base class, and the constructor body of the base class. The derived constructor body runs last, and therefore you know that all the stuff it accesses has already been created.
While we're at it: note that methods in C# traditionally begin with a capital letter.
Also, there is not really a good reason shown in this code to do the copying at all. You already have access to the base class members from the derived class, so why are you copying them into the derived class?
If i access either static or non static variable | function inside any of derived class function it working fine.
Why i can't access directly in a class. Why its not showing error when i access inside of any derived class function. Any one please clarify my doubts.
In other words you question is: Why can I access the static fields at the class level (outside of any methods or properties) but not instance fields.
Static fields are per class. You do not need an instance of the class but you need the class to be available. Therefore, if the class is available, then you can access it.
Now let's go to non-static fields. Here is your class, please note the numbers in comments:
class B : A {
string copyMsg1 = msg1; <-- 1. assign non-static to non static
string copyMsg2 = msg2; <-- 2. assign static to non static
string getMsg1 = alert1(); <-- 3. non static calling non-static
string getMsg2 = alert2(); <-- 4. non static calling static
void display() {
msg1 = "";
msg2 = "";
alert2();
}
}
This is NOT allowed because they are both instance fields (non-static), and there is no guarantee that there will be an instance of A available at this point.
This is allowed because instance fields can access static fields. But not the other way around because an instance may not be avaialbe. Instance fields, methods, and properties can access both static and non static.
This is NOT allowed because of item 1 above.
This is allowed because of 2.
Call the non-static method inside a setter method :
class A
{
protected string alert()
{
return "me";
}
}
class B :A
{
private string s;
private void setS()
{
s = alert();
}
}

Child static constructor not called when base member accessed

I have a class defined as:
public class DatabaseEntity<T> where T : DatabaseEntity<T> {
public static string Query { get; protected set; }
public static IList<T> Load() {
return Database.Get(Query);
}
}
public class Node : DatabaseEntity<Node> {
static Node() {
Node.Query = #"SELECT Id FROM Node";
}
}
When I run Node.Load() from a codebehind (Window.xaml.cs) the Node's static constructor never fires; or at least doesn't hit a breakpoint and does not set Node.Query to anything other than null.
Is there any reason why this might occur?
Solution
Check out the answers below for a few solutions. For my case, I decided to simply make the Query variable public, and set all instances of Query in one place. (Not ideal, but it works.)
The problem lies in your assumptions about when a static constructor is called. The documentation, which isn't the clearest, states that
It is called automatically before the first instance is created or any static members are referenced.
You may assume that if you call
Node.Load();
that you are calling a static method on the Node class, but in fact you're calling it on the base class, as that is where it is implemented.
So, to fix this, you have two choices. First, you can trigger the static constructor explicitly by creating a new instance of the Node class prior to calling Load()
var foo = new Node(); // static ctor triggered
Node.Load();
or create a protected virtual member that the base class can call in order to get the query value (can't use abstract here, unfortunately)
public class DatabaseEntity<T> where T : Derp {
protected abstract string Query { get; }
public static IList<T> Load() {
return Database.Get(new DatabaseEntity<T>().Query);
}
}
Both of which are hacky. Better to dispense with the statics altogether and go with instance methods. Statics should be used sparingly, as they result in tight coupling and other design headaches such as this.
Yes, static constructors will not be called till the members of the class is first accessed or first instance is created.
In your case you're accessing DatabaseEntity<T>.Load, so static constructor of DatabaseEntity<T> will be called not its derived class ones.
Even though you call Node.Load it is mapped to DatabaseEntity<Node> at compile time. So technically you're not accessing Node class at all.
You can also call class constructors directly using System.Runtime.CompilerServices and the RuntimeHelpers type by doing something as follows:
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
So for example you could use reflection to loop over all types in an inheritance chain and call each of the static constructors.

Why a member method of class is called before the Constructor

Generally, Constructor is the very first thing to be executed in class when it's instantiated.
But in following case, A member methods of the class are executed first & then the constructor.
Why is it so?
A Code Scenario :
namespace AbsPractice
{
class Program
{
static void Main(string[] args)
{
SavingsCustomer sc = new SavingsCustomer();
CorporateCustomer cc = new CorporateCustomer();
}
}
public abstract class Customer
{
protected Customer()
{
Console.WriteLine("Constructor of Abstract Customer");
Print();
}
protected abstract void Print();
}
public class SavingsCustomer : Customer
{
public SavingsCustomer()
{
Console.WriteLine("Constructor of SavingsCustomer");
}
protected override void Print()
{
Console.WriteLine("Print() Method of SavingsCustomer");
}
}
public class CorporateCustomer : Customer
{
public CorporateCustomer()
{
Console.WriteLine("Constructor of CorporateCustomer");
}
protected override void Print()
{
Console.WriteLine("Print() Method of CorporateCustomer");
}
}
}
That's because when you call SavingsCustomer ctor, first of all its base class ctor is called; in Customer ctor you call Print that's an overridden method.
So basicly before SavingsCustomer ctor instructions are executed, Customer ctor must be completely called.
Note that when you call Print from Customer, SavingsCustomer.Print() is executed.
This is the expected behaviour; if you want your classes to behave differently, you must change their logic. Maybe you shouldn't call an abstract method from base constructor, just to avoid what you're seeing now...
You should never, never do this unless you have a very good reason.
Calling a virtual method from a constructor is a disaster waiting to happen.
In C# object construction follows the class hierarchy order; that is, when a constructor is invoked, the most base class constructor is called first, then the immediately derived class constructor, then the next, etc. etc. (if I'm not mistaken, in C++ it's the other way around which can lead to even more confusion).
So when you call a virtual method from a constructor what really happens is that the virtual method, if overridden (which in your case is a guarantee), will be executed before the implementing class constructor is invoked. This means that the method could be executed before the object's state has been correctly initialized (normally via the constructor; if the method does not depend on any object state then this pattern is not an issue although I'd still not recommend it).
If it is absolutely necessary to use this pattern, good practices recommend implementing an Initialize() method and do any virtual calls form there. Enforcing consumers to call Initialize before using the object is a trivial task and you guarantee that the object's state will always be valid when the virtual call is made.
Tricky question.When You Create an object like this
SavingsCustomer sc = new SavingsCustomer();
It invokes constructor of Customer[base of class SavingsCustomer],means Customer()
- which inturn invoke Print() from class SavingsCustomer as it is abstract in Customer Class.
Eventhough it is a member function of SavingsCustomer it can be called from Customer class before calling constructor of SavingsCustomer Becuase Print() is declared as abstract method so it is shared by these two classes.
Same happens in the following declaration
CorporateCustomer cc = new CorporateCustomer();
Print() from CorporateCustomer class is called since SavingsCustomer.Print() is overrided

Why is my inherited class not hiding my base class method?

I have a project which uses Autofac to instantiate the objects
builder.RegisterType<AbcWebWorkContext>().As<IWorkContext>().InstancePerHttpRequest();
This AbcWebWorkContext is a subclass of WebWorkContext:
public partial class AbcWebWorkContext : WebWorkContext
In my AbcWebWorkContext I would like to hide a method and a property from the parent class
protected new Customer GetCurrentCustomer(){ //do stuff }
new public Customer CurrentCustomer { //do studd }
But when someone calls
_workContext.CurrentCustomer
The base class property is called. If I call it like this
((AbcWebWorkContext) _workContext).CurrentCustomer
it works.
I would like to know why I am not able to hide the parent method.
I can't change the called class because it is in NopCommerce's core, which I would not like to change.
Why is it not hiding the method?
Base class declaration of the methods:
protected Customer GetCurrentCustomer() { // do stuff }
public Customer CurrentCustomer{ // do stuff }
calling GetType() on _workcontext will output
{Name = "AbcWebWorkContext" FullName = "Nop.Web.Framework.AbcWebWorkContext"}
The type hierarchy is IWorkContext (interface) « WebWorkContext « AbcWebWorkContext
_workContext is declared as IWorkContext and Autofac generates an instance as AbcWebWorkContext (as shown above)
The new keyword means that the subclass's method hides the baseclass's CurrentCustomer instead of overriding, so WebWorkContext.CurrentCustomer is a completely different method than AbcWebWorkContext.CurrentCustomer.
You must declare the base class's method as
virtual Customer CurrentCustomer { ... }
And the subclass's method
override Customer CurrentCustomer { ... }
I suggest you read more about polymorphism in c#.
If the methods you're using are actually defined in an interface, IWebWorkContext, you simply encapsulate the base class rather than inheriting from it, like this:
class AbcWebWorkContext : IWebWorkContext
{
private WebWorkerContext _inner = new WebWorkerContext();
public Customer CurrentCustomer { ... }
}
If you can't make the base class's method virtual, you have to do something much less elegant, like reflection:
var prop = _workContext.GetType().GetProperty("CurrentCustomer");
var value = (Customer)prop.GetValue(_workContext, new object[0]);
I'm not sure if I got your questions right, but I think you need to add a virtual modifier to the method in base class and add a override modifier to method in the subclass.
Find out more on MSDN

Private constructor and public parameter constructor

I heard that a private constructor prevents object creation from the outside world.
When I have a code
public class Product
{
public string Name { get;set;}
public double Price {get;set;}
Product()
{
}
public Product(string _name,double _price)
{
}
}
Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?
I need a detailed explanation please.
The reason you would use the pattern you're describing is when you want to control how the object is instantiated.
In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.
If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).
Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.
Constructors can be chained together to avoid having to duplicate code. It is quite common to have private constructors, that nobody is supposed to call outside of the class, that are chained from a public constructor.
Example:
public class Test
{
private Test(int? a,string b) { }
public Test(int a) : this(a, null) { }
public Test(string b) : this(null, b) { }
}
Here there are two public constructors, one taking a string and one taking an int. They both chain to the common private constructor that takes both arguments.
Also, you can construct new objects from within the same class by using the private constructor. For instance, when you want specialized constructors only available through static factory methods:
public static Test Create()
{
int? a = ReadConfigurationForA();
string b = ReadConfigurationForB();
return new Test(a, b);
}
When it is not be a good idea to expose a private constructor to the outside world, add a static factory method that fetches the correct arguments to pass on the constructor.
You need a private constructor when you only want that constructor to be called from within the class itself. In your example you are forcing the calling object to provide 2 parameters when creating the object.
With a private constructor you could do something like:
public static GetInstance ()
{
return new YourObject();
}
but nothing else except the object could call the parameterless constructor.
It's commonly used to create a singleton pattern:
http://www.dofactory.com/Patterns/PatternSingleton.aspx
You would use a constructor with parameters when you wanted to force calling code to pass a value to the constructor in order to create an instance of your class. In your example, calling code must use the parameter version of the constructor in order to create a Product.
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
For more details refer to this:
http://msdn.microsoft.com/en-us/library/kcfb85a6(VS.80).aspx

Categories

Resources