What does inheriting from :this() means? [duplicate] - c#

This question already has an answer here:
what is 'this' constructor, what is it for
4 answers
I am watching a C# course and a part of code caught my eyes which was not explained in the tutorial.
Public Product(int productId, string productName, string description) : this()
{
this.ProductId = productId;
this.ProductName = productName;
this.description = description;
}
what does :this() means in the costructor ?

The : indicates the start of the initializer list. this() invokes the default constructor Product(), which could be defined implicitly or explicitly.
If there is a constructor defined, which takes one or more arguments, then there is no default constructor defined implicitly.
Your example constructor Product(int productId, string productName, string description) will only compile if there is a default constructor Product() explicitly defined in the same class because the default constructor Product() is not defined implicitly in this case.
The explicitly defined constructor Product() will be invoked before the code in the body of Product(int productId, string productName, string description) is executed. If Product() is empty (and has no initializer list), it won't do anything.

Related

Access specifier for constructors in C#

Can I have constructors with same parameter list but one private and one public or any other access specifier in C#.
Thanks in advance.
No, you can't overload either constructors or methods by just varying access modifiers (or return types in the case of methods). You can only overload members if they have different signatures.
Can I have constructors with same parameter list but one private and one public or any other access specifier in C#.
No - the access is not part of the method signature, so that would be a collision. Think about it, how would the compiler know whether to bind to the public or private constructor?
A constructor can be looked at as a special method. The constructor is called implicitly by the framework when an instance is created. but the overloading criteria for both methods and constructors are the same.
You cannot overload by return type or access modifiers in C#.
You can only do so by having different type of parameters or different number of parameters which also can be called as the method signature.
From MSDN http://msdn.microsoft.com/en-us/library/aa268049%28v=vs.60%29.aspx:
8.6.6 Constructor Overloading
Overloading of constructors is identical in behavior to overloading of methods. The overloading is resolved at compile time by each class instance creation expression (§15.8).
What I generally do in this circumstance is have a private "initializer" constructor that one or more other constructors invoke. This, of course, demands that you have a different parameter list. For example (very pedantic):
private Person ( String firstName, int age )
{
this.firstName = firstName;
this.age = age;
}
public Person ( String firstName, String lastName, int age )
:this(firstName, age)
{
this.lastName = lastName;
}
This takes advantages of constructor chaining to do something I call accumulative construction.
Although this example has a private constructor, it's pedantic and you probably would not have a need for it in this particular example--it's just to show the concept.
No, you can't.
You can create a private constructor and any number of static methods (with whatever access modifiers you prefer) which return an instantiated object.
public class MyClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
private MyClass() {}
public static MyClass InstanceWithProp1(string prop1)
{
return new MyClass() {Prop1 = prop1};
}
public static MyClass InstanceWithProp2(string prop2)
{
return new MyClass() {Prop2 = prop2};
}
}

Beginner to C#: How to do constructor chaining, overriding and using :this / :base?

I've studied Java last year and I don't think I ever had issues with writing constructors. I'm unfortunately so confused at how overloading and chaining in C# works, or even the basic concept of it.
I've seen :base get used in inheritence, but I'm not sure how.
I've seen :this get used in many places, and it always boggles me why it's used.
Here's an example of some code with :this (made public variables without setters/getters for sake of argument).
public class Person
{
public string firstName;
public string lastName;
public string height;
public int age;
public string colour;
public Person():this("George", "Seville", "45cm", 10, "Black")
{
// This is the default constructor, and we're defining the default
values.
}
public Person(string firstName, string lastName, string height, int age,
string colour)
{
this.firstName = firstName;
this.lastName = lastName;
this.height = height;
this.age = age;
this.colour = colour;
}
}}
I can only understand how the first constructor is being used e.g. making a simple object of "Person" would give it the default values. That's as far as I can understand. This code is unfinished since it shows 2 default constructors. I'd like to be able to overload and chain for every variant available i.e. 1 parameter, 2 parameter... so they all overload and chain appropriately.
So it should kind of (might not be right) look like this:
public Person():this("George", "Seville", "45cm", 10, "Black")
{
// This is the default constructor, and we're defining the default
values.
}
public Person(string firstName):this(firstName, "George", "Seville", "45cm",
10, Black)
{
this.firstName = firstName;
}
public Person(string firstName, string lastName):this(firstName, lastName,
"Seville", "45cm", 10, Black)
{
this.firstName = firstName;
this.lastName = lastName;
}
Of course I'm not sure if any of the code above makes sense, but I've seen some Classes with constructors with :this for each of them, and each constructor links to the one below it until the user can create an Object with any combination of parameters defined.
As for :base, this completely confuses me. Here's an example I've actually found online:
public class Circle:Shape
{
public Circle():this(Color.Black, new Point(0,0), 1)
{
}
public Circle(Color Colour, Point Position, double Radius):base(Colour,
Position)
{
this.Radius = Radius;
}
I think :base refers to the parent class, but I'm not sure why and how. Also, why is :this being used in the first constructor and not :base?
There are the 2 aspects I'm very confused with. Using :this and :base and understanding exactly how constructor chaining and overloading works. Please let me know if my question is too abstract. I've tried to be as specific as possible.
Thank you all so much for your support and time. Much appreciated!
I'll try to explain it as simple as I can.
Constructor overloading
Nothing new here, it's just like overloading any other method - You simply need the same name but a different signature (meaning different parameters passing into the constructor).
Constructor chaining
This is done by using the keyword this - just like in the code samples in your question.
btw, I usually use it to go from the most elaborate constructor to the simplest one.
sample code:
public class Person
{
public Person()
{
Children = new List<Person>();
}
public Person(string firstName)
: this()
{
this.FirstName = firstName;
}
public Person(string firstName, string lastName)
: this(firstName)
{
this.LastName = lastName;
}
public string FirstName { get; }
public string LastName { get; }
public IEnumerable<Person> Children { get; }
}
Of course, setting default values to properties by using constructor chaining is a valid design and I've used it myself when I needed it, but that's usually not the case.
The keyword base
This keyword always refers to the base (or parent) class.
You will see it a lot when overriding methods and properties as well.
When it comes to constructors - your assumption is correct - it does refer to the base (or parent) class.
So when used in a constructor (like in your Circle example), you can control what overload of the base constructors your derived (or child) class constructor will execute.
So, for instance, if your base class contains three constructors, you can choose which one of them you want to call.
c# will chain constructors of derived class to the default constructor of the base class unless specified otherwise.
Please note that if you inherit from a class that has no default (meaning: parameterless) constructor you must specify the : base(...) in your constructors, even if there is only one constructor to your base class (since that's the only way you can pass the needed parameters to it).
Generally speaking : this(...) refers to a constructor of the current class. As in your example this can be used to avoid code duplication. I think the example given does not make too much sense, from a logical perspective, but it's legal C# and - basically - how : this(...) is used
The second example is a mit more logical - or coherent, as the default constructor provides sensible default values to pass to the parametrized constructor.
This is the default constructor, which creates sensible defaults for the values to pass to the parametrized constructor:
public Circle():this(Color.Black, new Point(0,0), 1)
This is the parametrized constructor it passes the parameters that are also needed by the base class to the constructor of Shape:
public Circle(Color Colour, Point Position, double Radius):base(Colour, Position)
If you need a standard circle you can create one with
var shape = new Circle();
If you on the other hand, need a circle at a specific position, with a specific color and a specific radius, you can create one with the parametrized constructor
var shape = new Circle(Color.Silver, new Point(1,2), 5);
I think :base refers to the parent class, but I'm not sure why and how
base is a keyword to access members of the parent class.
1) var p = base.Property; will access a field or property from the parent class
2) base.Method(); will access a method from the parent class
3) base(..) will access a constructor from the parent class
why is :this being used in the first constructor and not :base?
this is the keyword to access memebers of the very same class. There are 3 parameters which define the properties of a Circle. Circle and Shape share only 1 property: color. So the default constructor calls the more specialized constructor of the same class Circle (that's why this()) and the second constructor passes the shared property color to the parent to be dealt with.
public class Circle:Shape
{
public Circle():this(Color.Black, new Point(0,0), 1)
{
}
public Circle(Color Colour, Point Position, double Radius):base(Colour,
Position)
{
this.Radius = Radius;
}
}
In your example, "base" refers to Shape(Color Colour, Point Position), "this" refers to Circle(Color Colour, Point Position, double Radius).
The first constructor is accessing the second one in the definition, which is why it is using :this.
The second constructor is using the constructor defined in the base class, which is why it is using base:
If you create an instance of Circle using:
Circle()
It would use the first constructor, which would call the second constructor (adding the parameters it requires), which would call the constructor in the base class.

Definition of 'this' keyword in .NET documentation

I currently trying to learn about 'this' keyword, in .NET documentation is:
The this keyword refers to the current instance of the class and is
also used as a modifier of the first parameter of an extension method.
First thing I learned with 'this' keyword was how to resolve scope ambiguity, when class data field have same name as for example parameter in constructor. Like this:
class Person
{
public string name;
public Person(string name)
{
this.name = name;
}
}
here is used 'this' keyword to inform C# compiler that I want to use variable named 'name' and it should be from current class instance scope rather then from method scope. For example if I create object of Person class on managed heap and reference to this object I assigned to variable named 'p1', statement 'this.name' would in fact be 'p1.X' (I know I cant write it to code like that, but just for better imagination). If it is right like that, then definition from .NET documentation make sense to me for this example.
but what if I use 'this' keyword for chaining constructors?
again I know what it does, but I really don't know what 'this' keyword is using from current class instance? In first example with scope ambiguity it make sense, but in chaining constructors I really don't know what it has to do with any class instance, as it doesn't use anything from instance, it just passing forward the incoming arguments to the master constructor.
Example of chaining constructors:
class Person
{
public string name;
public int? age;
public Person(string name): this(name, null) { }
public Person(string initName, int? initAge)
{
name = initName;
age = initAge;
}
}
So my question is, because in documentation is written, that this keyword refers to the current instance of the class:
What 'this' keyword is referring from current instance of the class when you use it with chaining constructors?
Thank you for answers
What 'this' keyword is referring from current instance of the class when you use it with chaining constructors?
It refers to a constructor call from this class (in comparison to constructors from the base class).
public MyClass(string name, string id) : this(name)
this mean you will use another overload constructor from same class.
public class Person
{
public Person(string name) : this(name, 0) // will call constructor with two arguments
{ }
public Person(string name, string id)
{
Name = name;
Id = id;
}
}

C# What does : this() mean after a constructor of struct [duplicate]

This question already has an answer here:
what is 'this' constructor, what is it for
4 answers
Could you answer, what does : this() mean after a constructor of struct?
public struct BaseProject
{
public BaseProject(string project)
: this()
{
this.Project = project;
}
public string Project { get; private set; }
}
What does : this() mean after a constructor of struct?
The this keyword in C# refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
As it pertains to a struct and the constructor of a struct, it actually is meaningless and does nothing. In C# a struct doesn't have a parameterless constructor. They are very similar to class constructors but differ in the following ways:
Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
A struct cannot have an initializer in the form: base (argument-list).
As such, the : this() after the struct constructor does nothing and is redundant - it can be removed with no issues whatsoever. However, in the context of a struct constructor, the this keyword works as expected.
Classes
When used in after a constructor, it invokes another constructor in the same class first - in this specific situation the parameterless constructor. This can be used to initialize other various parts of an object instance as they are invoked first.
Constructors
Read "using constructors" on MSDN for more details.
Consider the following:
public class FooBar
{
public int Number { get; }
public string Name { get; }
public FooBar()
{
Number = 10;
Name = "Pickles";
}
public FooBar(int number) : this()
{
Number = number;
}
public FooBar(int number, string name) : this(number)
{
Name = name;
}
}
var fooBar1 = new FooBar();
var fooBar2 = new FooBar(20);
var fooBar3 = new FooBar(77, "Stackoverflow");
// The following would be true
// fooBar1.Number == 10 and fooBar1.Name == "Pickles"
// fooBar2.Number == 20 and fooBar2.Name == "Pickles"
// fooBar3.Number == 77 and fooBar2.Name == "Stackoverflow"
The this keyword in the context of a constructor can also be used (as shown above) to call into parameterized constructors as well. If you were to inherit then you could call into default or parameterized constructors of the base class using the base keyword.
A constructor can invoke another constructor in the same object by
using the this keyword.
From Using Constructors (C# Programming Guide)
So in your example, when the constructor that takes a string is called, the parameterless constructor is (implicitly) called first, followed by the method body of the constructor that takes a string being executed.
It means it's calling the parameterless constructor of the type.

C# language - usage of “this” keyword [duplicate]

I was looking at sample code from MSDN just now and came accross:
namespace IListSourceCS
{
public class Employee : BusinessObjectBase
{
private string _id;
private string _name;
private Decimal parkingId;
public Employee() : this(string.Empty, 0) {} // <<--- WHAT IS THIS???
public Employee(string name) : this(name, 0) {}
It calls the other constructor in that class with that signature. Its a way of implementing the constructor in terms of other constructors. base can also be used to call the base class constructor. You have to have a constructor of the signature that matches this for it to work.
this lets you call another constructor of Employee (current) class with (string, int) parameters.
This is a technique to initialize an object known as Constructor Chaining
This sample might help some of the different derivations... The first obviously has two constructor methods when an instance is created... such as
FirstClass oTest1 = new FirstClass();
or
FirstClass oTest1b = new FirstClass(2345);
The SECOND class is derived from FirstClass. notice it too has multiple constructors, but one is of two parameters... The two-parameter signature makes a call to the "this()" constructor (of the second class)... Which in-turn calls the BASE CLASS (FirstClass) constructor with the integer parameter...
So, when creating classes derived from others, you can refer to its OWN class constructor method, OR its base class... Similarly in code if you OVERRIDE a method, you can do something IN ADDITION to the BASE() method...
Yes, more than you may have been interested in, but maybe this clarification can help others too...
public class FirstClass
{
int SomeValue;
public FirstClass()
{ }
public FirstClass( int SomeDefaultValue )
{
SomeValue = SomeDefaultValue;
}
}
public class SecondClass : FirstClass
{
int AnotherValue;
string Test;
public SecondClass() : base( 123 )
{ Test = "testing"; }
public SecondClass( int ParmValue1, int ParmValue2 ) : this()
{
AnotherValue = ParmValue2;
}
}
A constructor is a special method/function that is ran to initialize the object created based on the class. This is where you run initialization things, as setting default values, initializes members in all ways.
"this" is a special word which points so the very own object you're in. See it as the objects refereence within the object itself used to access internal methods and members.
Check out the following links :
C# When To Use “This” Keyword
When do you use the “this” keyword?

Resources