The this reference? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When do you use the “this” keyword?
Can anyone explain me the "this" reference? when we use this ? with a simple example.

When you use this inside a class, you're refering to the current instance: to the instance of that class.
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName) {
//How could you set the first name passed in the constructor to the local variable if both have the same?
this.firstName = firstName;
this.lastName = lastName;
}
//...
}
In the above example, this.firstName is refering to the field firstName of the current instance of the class Person, and firstName (the right part of the assignment) refers to the variable defined in the scope of the constructor.
So when you do:
Person me = new Person("Oscar", "Mederos")
this refers to the instance Person instance me.
Edit:
As this refers to the class instance, cannot be used inside static classes.
this is used (too) to define indexers in your classes, like in arrays: a[0], a["John"],...

this is a scope identifier. It is used within an object's instance methods to identify behaviors and states that belong to an instance of the class.

Nowadays-fashionable Fluent APIs use this extensively. Basically it's used to get hold of a reference to the current instance.

here's a simple example
public class AnObject
{
public Guid Id { get; private set;}
public DateTime Created {get; private set; }
public AnObject()
{
Created = DateTime.Now;
Id = Guid.NewGuid();
}
public void PrintToConsole()
{
Console.WriteLine("I am an object with id {0} and I was created at {1}", this.Id, this.Created); //note that the the 'this' keyword is redundant
}
}
public Main(string[] args)
{
var obj = new AnObject();
obj.PrintToConsole();
}

Related

C# classes init function

I am learning c#, having used python before, and i have started to use classes in my work.
Python has the __init__() function to initialise a class, for example:
class name():
__init__(self):
# this code will run when the class is first made
Is there a similar function for c# classes?
currently, I am creating a normal function inside the class and having to call it straight after it is made.
You have to use one or more constructor for that:
see this link on learn.microsoft.com.
For example:
public class Person
{
private string last;
private string first;
// This constructor is called a default constructor.
// If you put nothing in it, it will just instanciate an object
// and set the default value for each field: for a reference type,
// it will be null for instance. String is a reference type,
// so both last and first will be null.
public Person()
{}
// This constructor will instanciate an object an set the last and first with string you provide.
public Person(string lastName, string firstName)
{
last = lastName;
first = firstName;
}
}
class Program
{
static void Main(string[] args)
{
// last and first will be null for myPerson1.
Person myPerson1 = new Person();
// last = Doe and first = John for myPerson2.
Person myPerson2 = new Person("Doe", "John");
}
}
Your talking about constructor in c#
class MyClass{
public MyClass{ //this is the constructor equals to pythons init
}
}
These concepts are available in almost all languages with different format
You should start building a constructor like this:
public class Car
{
public string plateNumber {get; set;}
public Car(string platenumber)
{
this.plateNumber = platenumber;
}
}
And then initialize an instance of it in another form or class like so:
Car myCar = new Car("123abc");

C# Methods and Properties [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
When to use Methods and Properties in C#?
They can do same thing but when to use both of them.
And also is it possible to set a whole object via C# Property instead of single value.?
A property is more or less what we use to describe different things about a class. They let us define what a class can do and essentially what that class is all about. Consider the following:
namespace Example
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
}
Name, Age, and Birthday would be considered properties of the Person class. They define what a person is and give us a way to give the class value. A method would then be used to do various things with the properties. You could write a method to get or set the value of a property such as:
public string GetName()
{
return Name;
}
public void SetName(string name)
{
Name = name;
}
However these would be pointless considering the Name property is public meaning it can be accessed whenever we create an instance of the Person class. The above methods would be used if we wanted to set the Name property, but keep it private. Another example of a method would be if we wanted a way to say create a new instance of the person class. By default visual studio will let you instantiate a new Person object like so:
Person jim = new Person();
However we can also write our own "constructor" method to allow us to create a new Person and set it's properties at the same time.
public Person(string name, int age, DateTime birthday)
{
Name = name;
Age = age;
Birthday = birthday;
}
Now we have an easy, streamlined way to instantiate a new Person object which uses a constructor method, and we can create a new Person object like so:
Person jim = new Person("Jim", 25, DateTime.Today);
But the use of methods dont stop there. Since DateTime is the way we represent the Birthday property, we could write a method that could convert a string into the appropriate DateTime.
public DateTime ConvertToDateTime(string date)
{
DateTime temp;
DateTime.TryParse(date, out temp);
return temp
}
Now we can change our constructor to look like this:
public Person(string name, int age, string birthday)
{
Name = name;
Age = age;
Birthday = ConvertToDateTime(birthday);
}
And can instantiate a new Person object like this:
Person jim = new Person("Jim", 25, "1/10/1995");
On a final note, as #vivek nuna said, find a good book! A great one that I've used in previous C# classes would be Murach's book on C#. Also MSDN.com has all the documentation you would need to learn how to code in C#. Try this link to learn more about properties or this link to learn more about methods. Finally, an excellent tutorial I found to learn C# is Scott Lilly's Guide to C#. Not only will you learn the ins and outs of C#, you will get to build a pretty neat and simple text-based RPG!
An proppertie is just a short hand and will create at the background an public get method and a public set
method and a private field to store the value.
// example propertie
public string Name { get; set; }
// at run time it is the same as:
private string Name;
public string GetName(){
return this.Name;
}
public string SetName(string name){
this.Name = name;
}
See Image : the sample class only has an proppertie in code but if you use Reflection to get all the members off the Sample class you will see that at run time these methods are generated but not visable in code.
set_name()
get_name()
'notice the private field Name is not shown because it is private and not visable for the outside, but is genrated.'

C# static and non-static string variables in a formatted string as parameters

As a newbie in C#, I am trying to figure out why I have to put CardNumber as such as static in order to fit into the formatted string....
If I didn't add static string CardNumber but use string CardNumber;, the code would report an error with the last CardNumber underlined. The error goes: A field initializer cannot reference the non-static field, method, or property 'WriteXML.CardNumber'.
I know there are tons of static and non-static comments and questions out there. None of them seems to directly explain, "if using non-static in a formatted string, then _ will happen, or then _ won't make any sense". If duplicate, please kindly point out the resource at least. I really appreciate it!
class WriteXML
{
static string CardNumber;
static string ExpMo;
static string ExpYr;
static string FirstName;
static string LastName;
string xmlContent =
string.Format("<CardNumber>{0}</CardNumber>" +
"<ExpMo>{1}</ExpMo>" +
"<ExpYr>{2}</ExpYr>" +
"<FirstName>{3}</FirstName>" +
"<LastName>{4}</LastName>",
CardNumber, ExpMo, ExpYr, FirstName, LastName);
}
Field initializers run before the object is fully constructed, so they can't access other fields in the same object because those fields might not be initialized yet. The order that field initializers run in is not guaranteed.
For example, if you had something like:
public class Foo
{
string someField = "foo";
string someOtherField = someField + "bar";
}
Then the initialization of someOtherField can't happen until someField has been initialized.
So you have to initialize someOtherField somewhere else, once the object has been constructed and all the field initializers have run. One place would be the constructor:
public class Foo
{
string someField = "foo";
string someOtherField; // can't initialize yet
public Foo()
{
someOtherField = someField + "bar";
}
}
Another alternative, especially if someOtherField isn't supposed to be writable, would be to use a property:
public class Foo
{
string someField = "foo";
)string SomeProperty
{
get { return someField + "bar"; }
}
}
This defers working out what SomeProperty is until you actually try and access it and, as a bonus, if someField is changed after construction, then SomeProperty will automatically synch up to the new value.
For example:
var f = new Foo();
Console.WriteLine(f.SomeProperty); // displays "foobar"
// assuming we'd marked it public
f.someField = "la"; // assuming we'd made that public too!
Console.WriteLine(f.SomeProperty); // displays "labar"
The answer to this question is found in C# Language Specification:
A variable initializer for an instance field cannot reference the
instance being created. Thus, it is a compile-time error to reference
this in a variable initializer, as it is a compile-time error for a
variable initializer to reference any instance member through a
simple-name.
In your code below, xmlContent is an instance field that has a variable initializer than references instance members CardNumber, ExpMo, ExpYr, FirstName, LastName. They are instance members when you omit the static field modifier. So it is not up to the spec, and hence the compile-time error.
string xmlContent =
string.Format("<CardNumber>{0}</CardNumber>" +
"<ExpMo>{1}</ExpMo>" +
"<ExpYr>{2}</ExpYr>" +
"<FirstName>{3}</FirstName>" +
"<LastName>{4}</LastName>",
CardNumber, ExpMo, ExpYr, FirstName, LastName);
See #Matt Burland's answer how to work around this issue.
I am not really sure what you are trying to achieve, but maybe this code will help you.
public class Foo
{
string CardNumber { get; set;}
string ExpMo { get; set; }
string ExpYr { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
public String WriteXml()
{
string xmlContent =
string.Format("<CardNumber>{0}</CardNumber>" +
"<ExpMo>{1}</ExpMo>" +
"<ExpYr>{2}</ExpYr>" +
"<FirstName>{3}</FirstName>" +
"<LastName>{4}</LastName>",
CardNumber, ExpMo, ExpYr, FirstName, LastName);
return xmlContent;
}
}
I'll try to quote and complete your desired explanation sentence:
If using a non-static reference in a formatted string (more general, in another non-static field), then that string/field will not be able to access it because it needs in the first palce a reference to an initialized object (non-static means that it can have different values based on different objects where the field lives in). Using a static field it can access anytime without needing an initialized object.

How do I access the nested Class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have the following three classes defined.
public class FrequencyRecord
{
public double Frequency;
public int Duration;
}
public class EntryRecord
{
public string Name;
public Boolean Status;
public long TotalTime;
public FrequencyRecord[] FreqTime = new FrequencyRecord[25];
public string Description;
}
public class Salv7Profile
{
public string Version;
public string SoftVersion;
public string Name;
public DateTime CreateDate;
public DateTime LastModDate;
public int Count;
public EntryRecord[] Entries = new EntryRecord[99];
public int Type;
}
Then I create an instance:
public static Salv7Profile IntProfile = new Salv7Profile();
Assigning a value to:
IntProfile.Name = "Peter";
works fine, But if I try:
IntProfile.Entries[1].Name = "Peter";
It throws an error: [System.NullReferenceException] "Object reference not set to an instance of an object."}
Being a novice at C#, how do I access the nested Entries class?
The problem is that you've created an array, but that array is just full of null references to start with. You'd need something like:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries[1] = record;
to replace the array element with a reference to the newly-created EntryRecord.
It would almost certainly be better if you changed Entries to be a List<EntryRecord> though, and just used:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries.Add(record);
or more briefly, using an object initialzier:
IntProfile.Entries.Add(new EntryRecord { Name = "Peter" });
I would also strongly recommend against having public fields; use properties instead, and consider making your types immutable if you can.
(I'd encourage to think about whether you really need the IntProfile field to be static, too... static fields imply global state, which is harder to test and reason about.)

Where and when to use "this" keyword [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When do you use the “this” keyword?
Hi All,
I am just wondering when and where using the keyword is a MUST? Because sometimes if I dont "this" or even I delete "this" the program just runs fine. So what will happen if you dont use it? or if you USE it in a wrong place.
Some explict examples would be appriciated.
The this keyword is often used to disambiguate between member variables and local variables:
...
{
int variable = 10;
this.variable = 1; // modifies a member variable.
variable = 1; // modifies the local variable.
}
....
The other use of this is to pass a reference to the current object so:
....
DoSomethingWithAnObject( this );
....
Another use (Thanks to HadleyHope ) is to disambiguate when method parameters are assigned to member variables with the same name:
void Initialise( int variable )
{
this.variable = variable;
}
You can't use this when calling static members. The compiler will just not let you. When you use "this" you are explicitly calling the current instance. I like to prefix current instance members with "this" even if this is not mandatory but just for clarity. That way I distinguish local scope variables from members.
Cheers
Microsoft recommend using camelCase for member variables, i.e.
public class MyClass
{
private int myInt;
private void SetMyInt(int myInt)
{
this.myInt = myInt;
}
}
So if you didn't have the 'this' keyword, there would be confusion between the private member and the parameter.
Personally I prefer prefixing my private members with an underscore to avoid this confusion.
private int _myInt;
So the only real use I find for it is to pass a reference of the current object to something else
MyStaticClass.MyStaticMethod(this);
public class People{
private String name;
private int age;
public People(String name, int age){
this.name = name;
this.age = age; //use this to declare that the age is the field in People class
}
}
One way to use this, hope it can help you.
You can use this when you have a member variable and a local variable of the same name in the same scope - the "this" will then make clear which one you mean.
Consider this:
class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public Person(string name)
{
this.name = name; // "this" is necessary here to disambiguate between the name passed in and the name field.
this.Name = name; // "this" is not necessary, as there is only one Name in scope.
Name = name; // See - works without "this".
}
}
Personally I use this whenever I'm accessing a member variable or method. 99% of the time it's not necessary, but I think it improves clarity and makes the code more readable - a quality well worth the extra effort of typing 4 characters and a dot.
This is a bit subjective, but if you are using a proper naming convention (I use _camelCase for member variables) you will never need to use this.
Except this exception: =)
When you want to call an extension method from inside the class that the extension method is for:
public class HomeController : Controller
{
public ActionResult Index()
{
// won't work
return MyCustomResult();
}
public ActionResult List()
{
// will work
return this.MyCustomResult();
}
}
public static class MyExtensions
{
public static MyResult MyCustomResult(this Controller instance)
{
return new SomeResult(instance.ActionName);
}
}
You don't have to use "this" keyword every time in your member method, it is useful in this case:
class human
{
private int age;
...
void func(int age)
{
this.age = age;
}
...
}
it can solve the confusion which age you mean

Categories

Resources