Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

: this(foo) syntax in C# constructors?

Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.

Can someone explain the purpose of ":this" or ":base" following a C# constructor method?

For example:

public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}

My gut feeling is that it is used to map a default argument onto another constructor method.

like image 221
FlySwat Avatar asked Dec 03 '08 19:12

FlySwat


People also ask

What is the foo function in C?

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. Foo and other words like it are formally known as metasyntactic variables.

Why is foo used in examples?

foo is used as a place-holder name, usually in example code to signify that the object being named, or the choice of name, is not part of the crux of the example. foo is often followed by bar , baz , and even bundy , if more than one such name is needed. Wikipedia calls these names Metasyntactic Variables.

What does foo return?

foo returns a pointer to this local variable - c . Save this answer. Show activity on this post. int *foo(int a) is the function signature of foo telling us the parameter is an integer and foo returns a pointer to an integer.

What does int foo mean?

int & foo(); means that foo() returns a reference to a variable.


1 Answers

You're basically right. this() calls a constructor on the current instance, base() calls the supertype's constructor on current instance. They're generally used to handle constructor overloads so you can add additional options without breaking things out into a separate method.

like image 130
MrKurt Avatar answered Oct 10 '22 06:10

MrKurt