[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Auto Implemented Properties - C#

Posted on 2011-04-22
15
Medium Priority
?
495 Views
Last Modified: 2013-12-16
Hi,

I have a class called Person. And it is like below. Can you please let me know in which internal  variable Name value will be stored ? I thought as like in VB.NET it is going to store in _Name variable. and i can access that variable in Print() method. But it did not in C# !!

public class Person
{
        public string Name { get; set; }

        public void Print()
        {
            Console.WriteLine(_Name);    // Error here
        }
}
0
Comment
Question by:milani_lucie
  • 4
  • 2
  • 2
  • +4
15 Comments
 
LVL 10

Expert Comment

by:Asim Nazir
ID: 35447902
Hi,

User Name instead of _Name.
0
 
LVL 10

Expert Comment

by:Asim Nazir
ID: 35447903
Use Name instead of _Name.
0
 

Author Comment

by:milani_lucie
ID: 35447952
But what is the internal variable name it is storing ?
0
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
LVL 2

Assisted Solution

by:Abhijit Marathe
Abhijit Marathe earned 336 total points
ID: 35447978
Hi,

The compiler will automatically generate the backing field at compile time if it finds empty get or set blocks saving you the work.  You can still add get and set blocks that have additional filtering logic in them.

If you open it using ILDASM command line tool. You will get following line for your automatic property name Name.
.field private string '<Name>k__BackingField'

If you still have some query then please let me know.
0
 
LVL 2

Expert Comment

by:Abhijit Marathe
ID: 35447997
Continue with my previous post

I think you cannot access it through code.
0
 
LVL 4

Accepted Solution

by:
HohlovDima earned 664 total points
ID: 35448009
Hi,
In C# you can't access it b/c it is defended by compiler and have coded name. Look at screenshot. I use reflector to see what was generated
 c#in VB we have another situation look at screen:
 vb
0
 

Author Comment

by:milani_lucie
ID: 35448041
I cannot do this:

public class Class1
{
        public string Name { get; set; }

        public void Print()
        {
            Console.WriteLine(<Name>k__BackingField);    // Error here
        }
}

I think so you are correct. As like in VB.NET, we cannot access internal variable. What do you think ?

Thanks
0
 
LVL 4

Assisted Solution

by:HohlovDima
HohlovDima earned 664 total points
ID: 35448079
Yes we can't get access to it.
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 35448272
You can access it via Reflection, but not sure why you want to.

Auto-generated backing fields will have the CompilerGeneratedAttribute (as shown by HohlovDima's picture).
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilergeneratedattribute.aspx

You can detect this with Reflection as well, in FieldInfo.
0
 
LVL 10

Expert Comment

by:Asim Nazir
ID: 35448418
I cannot see why you want to access internal variable?
why don't you just set and get he property itself?
Is there any specific reason?
0
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 332 total points
ID: 35449620
You don't need to know the name of the backing variable, you can simply refer to the property by it's name, or by using the "this" keyword in C# or "Me" in VB (I prefer the "this.PropName" usage just because it makes what the code is doing a little more obvious).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
	static void Main(string[] args)
	{
		Class1 c1 = new Class1();
		c1.Name = "Bubba";
		c1.PrintMethodOne();
		c1.PrintMethodTwo();
		Console.ReadKey();
	}
}
public class Class1
{
	public string Name { get; set; }

	public void PrintMethodOne()
	{
		Console.WriteLine(this.Name);
	}

	public void PrintMethodTwo()
	{
		Console.WriteLine(Name);
	}
}

Open in new window

0
 
LVL 1

Assisted Solution

by:ulfur
ulfur earned 668 total points
ID: 35451260
There are two versions you can use:
public class Person
{
	// this is the instance variable that will store the name
	private string _Name;
	// define the accessors if you need extra functionality, e.g. fire an event or update a control
	public string Name
	{
		get { return _Name; }
		set { _Name = value; }
	}
	public void Print()
	{
		// print the name to the console; the following two statements yield the same result
		Console.WriteLine(_Name); // direct access to the value
		Console.WriteLine(Name); // retrieve the value by calling the get accessor
	}
	}

Open in new window


The simple version is this:

public class Person
{
	// Name becomes the instance variable that stores the name
	public string Name;

	public void Print()
	{
		// print the name to the console
		Console.WriteLine(Name);
	}
	}

Open in new window


Hope this helps
0
 
LVL 10

Expert Comment

by:Asim Nazir
ID: 35451806
Ok. So if you really want to use variables, leave auto implemented properties and go for standars properties.
0
 
LVL 1

Assisted Solution

by:ulfur
ulfur earned 668 total points
ID: 35453011
That's right. You can find the details here Auto-Implemented Properties (C# Programming Guide)
"When you declare a property ... the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors."
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35456099
Probalby just a typo on ulfur's part, but since you accepted http:#a35451260, it's probably worth pointing out that the second code snippet in that comment doesn't have a property, it has a member variable.
0

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question