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

This question already has answers here:
what is 'this' constructor, what is it for
(4 answers)
Closed 6 years ago.
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.

Related

Initialize generic type with non-empty constructor

Referencing to that Question: Cannot create an instance of the variable type 'Item' because it does not have the new() constraint
I would like to create an instance from a generic type with a non empty constructor.
public class A{};
public class B
{
public B(int){/*...*/}
}
public class C
{
public static T validate<T>(int index)
where T : A,
new(int) //error
{
if(/*validation*/)
return null;
return new T(index);
}
}
If I try to call B b = validate<B>(42); I got this error:
'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C.validate(int)'
Question 1: Why can I use a parameterless constructors only?
Question 2: How can I solve my problem without delegates or interfaces?
(I am always looking for fancy solutions.)
Update for C# 11
The new static abstract/virtual members in interfaces feature, designed with generic maths in mind, but usable to require static factory functions for your type, is a great fit and I would recommend using it if you can change the type implementation.
Just add a static abstract T Create(your params come here...) to an interface, and then add a constraint in the form T : IYourInterface to your method.
Then, just use T.Create(...) to create an instance. Amazing, isn't it?!
Old Answer
You can use reflection to invoke the constructor:
var constructorInfo = typeof(T).GetConstructor(new[] { typeof(int) });
if (constructorInfo != null)
{
object[] parameters = new object[] { index };
return (T)constructorInfo.Invoke(parameters);
}
else
{
// handle it
}
(adapted from https://stackoverflow.com/a/13523659/5962841)
Or, you can use activator to create an instance (see #datrax's answer)
(T)Activator.CreateInstance(typeof(T), index)
The feature you asked for has already often been requested.
The request for the feature is being tracked here (github csharp design repo), but don't expect it this year, it's not even prototyped or accepted.
The problem here does not really lend itself to C# generics.
A generic type should have a common interface as far as properties & methods, that's the whole point of specifying T must be an instance of A or a subclass of A.
Here, A doesn't have an int constructor, but you want to create an instance of a subclass that does have an int constructor.
Also, from you code, B doesn't inherit from A, but you specified T: A in your generic method. Is that just an oversight?
Using Activator also relies on late binding, so if you call it for a class that doesn't have an appropriate constructor, you'll get a runtime error.
A functional approach is more intuitive, looks cleaner, and doesn't rely on runtime reflection.
public class A {
};
public class B:A
{
public B(int y){ x = y; }
public int x { get; }
}
public class C
{
public static T validate<T>(int index, Func<int, T> instantiator)
where T : A
{
if (false)
return null;
return instantiator(index);
}
}
class Program
{
static void Main(string[] args)
{
B b = C.validate<B>(42, (y)=>new B(y));
}
}
You are not allowed to pass any argument to the constructor of generic type. The only possible constraint is: where T :new ().
But anyway there's still a possibility to create such instance
(T)Activator.CreateInstance(typeof(T), index);

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?

Constructor with optional parameter violates new() constraint

I have a class with this constructor:
public Currency(Guid? vcurrencyUI = null)
: base(vcurrencyUI)
{ }
and I want to use this class with a new() constraint but I get this error:
'Currency' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method ...
If I split the constructor everything works fine:
public Currency(Guid? vcurrencyUI)
: base(vcurrencyUI)
{ }
public Currency()
: base()
{ }
why do I need to split the constructor?
Because a constructor with a default parameter is not a parameterless constructor.
Default parameters are "filled in" by the compiler at compile time. When you write:
var foo = new Currency();
The compiler generates:
var foo = new Currency(null);
When the class is compiled, the compiler creates a constructor that takes that Guid? parameter, and also generates some metadata that says in effect "if the parameter isn't supplied at compile time, then supply null." But no parameterless constructor is generated for the type.
The new() constraint requires that a parameterless constructor be defined for the type, and it won't accept a constructor with a single default parameter. Most likely that's because the runtime, which ends up having to call the constructor, doesn't understand the concept of default parameters.
Although Jim already answered your question, note that a more general approach might be to allow passing a delegate which would instantiate your concrete class, instead of forcing all your implementations to be parameterless.
I.e. instead of this:
public class Something<T> where T : new()
{
public T CreateInstance()
{
return new T();
}
}
You can pass an explicit delegate which will do any custom instantiation logic:
// note that the constraint is now removed
public class Something<T>
{
private readonly Func<T> _ctor;
public Something(Func<T> ctor)
{
_ctor = ctor;
}
public T CreateInstance()
{
return _ctor();
}
}
// and you can now pass arbitrary constructor logic as a delegate
var x = new Something<Currency>( () => new Currency(null) );
This also allows you to create a helper class and have both options readily available:
public class Something
{
// this allows you to use a parameterless ctor
public static Something<T> Create<T>() where T : new()
{
return new Something<T>(() => new T());
}
// this allows you to specify a custom one
public static Something<T> Create<T>(Func<T> ctor)
{
return new Something<T>(ctor);
}
}

C# constructor using this [duplicate]

This question already has answers here:
Call one constructor from another
(13 answers)
Closed 9 years ago.
Can somebody explain what means : this(123) in a constructor ?
public class MyObject
{
public MyObject(): this(123)
{
}
............
}
Because your class has another constructor which takes and int as parameter.
public class MyObject
{
public MyObject()
: this(123)
{
}
public MyObject(int x) //something like this
{
}
}
See: Using Constructors (C# Programming Guide)
A constructor can invoke another constructor in the same object by
using the this keyword.
This means, that you are calling another constructor with the fixed Value "123":
public class MyObject
{
public MyObject(): this(123)
{
}
public MyObject(int number)
{
}
}
Means: Whenever you call new MyObject(), without any parameter, it equals the call to new MyObject(123);
this is used to call one constructor from another within the same class.
Refer to this article for better understanding.
http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C
You have another constructor that accepts an int (thought it could be long or double, or anything else that int can implicitly cast to)
public class MyObject
{
public MyObject(): this(123)
{
}
public MyObject(int num)
{
//do something with the num
}
}
That means "before you execute what between the curly brackets, execute the suitable Constructor with parameters 123"
The syntax provided is used for "constructor chaining" whereby the specified constructor (which accepts an integer argument) is called before the body of the current constructor.

What are the different purpose of "new" is available in C#

Can any one explain in the detail(with example) the different purpose of the "new" in C#.
You have:
new operator:
Used to create objects and invoke
constructors
new modifier
When used as a modifier, the new
keyword explicitly hides a member
inherited from a base class
new constraint
The new constraint specifies that any
type argument in a generic class
declaration must have a public
parameterless constructor
Object instantiation
In anonymous types
To signal that a member of the base class is being hidden.
As a constraint
About 3 (from MSDN):
public class BaseC
{
public int x;
public void Invoke() { }
}
public class DerivedC : BaseC
{
new public void Invoke() { }
}
The keyowrd is not necessary but should be used to make it clear that the base-class constructor is being hidden.

Categories

Resources