O'Reilly logo

A Programmer's Guide to C# 5.0, 4th Edition by Nick Wienholt, Eric Gunnerson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

CHAPTER 12

image

Variable Scoping and Definite Assignment

In C#, local variables must be given names that allow all variables to be uniquely identified throughout the method. Consider the following:

using System;class MyObject{    public MyObject(int x)    {       x = x;    }    int x;}

Since the compiler looks up parameters before it looks up member variables, the constructor in this example does not do anything useful; it copies the value of parameter x to parameter x.1 You can fix this by adding this. to the front of the name that you want to refer to the member variable.2

using System;class MyObject{    public MyObject(int x)    {       this.x ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required