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.
Related
This question already has answers here:
Calling a static method on a generic type parameter
(9 answers)
Closed 3 years ago.
Example:
Public class a<T> where T: containsStatic
{
public void func()
{
T.StaticMethod();
}
}
Is it possible? And if not is there another way to do it?
EDIT:
it gives me the error: "'T' is a type parameter, which is not valid in the current context."
why is that? is there a way to fix this?
The problem I forsee with this is how do you guarantee that T supports StaticMethod?
However if you are sure that StaticMethod will always exist on T, you can use reflection to accomplish this fairly simply:
using System.Reflection;
public void func()
{
var staticMethod = typeof(T).GetMethod("StaticMethod", BindingFlags.Public | BindingFlags.Static);
staticMethod.Invoke(null, null);
}
Assume we wave a magic wand and you can do that now. Assume a type C:
public class C
{
public static void Foo()
{
}
}
How would this:
public class A<T> where T : C
{
public void Func()
{
T.Foo();
}
}
Be any different from:
public class A<T> where T : C
{
public void Func()
{
C.Foo();
}
}
It would not. It would have to be the same method being called. A static method call is generated statically (yeah, I know) when the method's code gets generated. The compiler seeing T.Foo() wouldn't possibly be able to insert any other call than C.Foo() there.
So you can't even express that in C#'s grammar, a type parameter is disallowed by the spec in such a context:
A type parameter cannot be used in a member access (Member access) or type name (Namespace and type names) to identify a static member or a nested type.
If you want to dynamically call a static method depending on T's value at runtime, refer to #Martin 's reflection solution.
You can call any static method, if it does not depend on the Generic Type.
If you have a class like
public class Test<T>
{
public static int Result => 5;
}
You can call
int n = Test<int>.Result;
at any place you want, and it is not important what type you actually insert, since any type will do the same
int n = Test<string[]>.Result;
will do the very same thing.
If your function depends on T like in
public class Test1<T>
{
public static void Action(T param)
{
}
}
You can use
Test1<int>.Action(8);
At any place you want.
Also inside other generic classes:
public class OtherClass<T>
{
public void Method(T param)
{
Test1<T>.Action(param);
}
}
But most often it is possible to write a generic function in a non-generic class like
public class Test2
{
public static void Action<T>(T param)
{
}
}
This works at any place in the Program
Test2.Action("string");
Test2.Action(9);
You can put this function in any class you want, since it's static. There is no need to put this function in a generic class.
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);
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.
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?
This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
When do you use the “this” keyword?
Best practices for using the ‘this’ keyword in C#
I have a style question regarding the this keyword. Do you use this when self-referencing auto-implemented properties or methods within a class for the sake of clarity?
For one example, in your Constructor, do you write your parameter assignments as:
public class Foo
{
public string FooProperty { get; set; }
public Foo(string fooProperty)
{
this.FooProperty = fooProperty;
}
...
}
OR as:
public class Foo
{
public string FooProperty { get; set; }
public Foo(string fooProperty)
{
FooProperty = fooProperty;
}
...
}
IMHO, the this is a very useful keyword. Once I see the "this", I know it is a class variable. Otherwise, I would have to check whether its a parameter, a variable declared within the method. "This" saves time :) (ambiguous joke hehe)