Jim Lynch Codes
  • Blog
  • About Jim

Writings about one coder's stories & experiences.

Variables in C# Quick-Start Refresher

1/4/2016

0 Comments

 
One of the great things about C# is how you handle variables. Variables are statically typed, have access modifiers, and can even use a nifty shorthand trick to easily and flexibly create "global" variables without wordy getter/setter methods. Let's dive in to how variables work in C#! 

Local Variables

Define a variable inside of a function, and it is only accessibly inside of that function. There is no var keyword in C#. Rather, as in Java, we write the data type of the variable, followed by the variable name, then a single equals sign and the value (optional when declaring the variable).
    // code here can not use material

    private void myFunction()
    {
         string material = "glass";

        // code here can use material

    }
        
    // code here can not use material
As in other languages, local variables are good for temporarily storing information for calculations and intermediate steps since they are easily garbage collected and don't hang around in memory. 

Instance Variables

Instance variables or field variables are available to the whole class. They are declared outside of any function in the class, and can use any of these access modifiers: public, private, or protected. Here is an example of the material variable that is accessible from anywhere inside of the class (but not to external classes):
    
    private string material = "glass";
    // code here can use material

    private void myFunction()
    {
        // code here can use material

    }
        
    // code here can use material

Public Variables Like a Pro

Suppose you wanted an external class to have access to the material variable. We can do this quite easily in Visual Studio. If you had a private class level variable as in the example above, and you wanted to make is visible to other class then you could just right-click on the variable name and go to Refactor -> Encapsulate Field. Doing this generates the following code:
    // before encapsulate method
    private string material = "glass";
 
    // after encapsulate method
    private string _material = "glass";

    public string material
    {
        get { return _material; }
        set { _material = value; }
    }
It's a good practice to create public variables like this because it prevents headaches later. Suppose later you decide that you want to change the name of the reference to the variable in the current class from _material to _originalMaterial. Now you can simply use ctrl + f to find and replace all occurrences in the file. Note that this won't break any references to the variable from other classes as they class still just access it with instanceVar.material. Without the encapsulation you would have to go to every class and change the variable name to the new name which is no fun, especially in big projects. 

Static Variables

Static variables, of course, belong to the Class itself, and not instances of the class. It's quite simple in C# to create static variables. Static variables can have either public, private, or protected access modifiers just as other variables do. Here's a quick example where material is a static variable: 
public class MyClass {
    
    public static string material = "glass";

    public void myFunction()
    {
        Console.WriteLine("The static material variable is: " + MyClass.material);
    }

}

Virtual Variables 

Suppose you want to make a variable that can be overridden by subclasses that extends from this class using inheritance. For example, with the code below you can have a function that accepts a Dog object and tries to access the .size property. If it is a Dog object, it will use the private _size property, but if it is a Beagle Object it will use the _size property from the Beagle class. This is normally the behavior you want, and here's how to do it:   
    
    public class Dog
    {
        private Size _size;
 
        public virtual Size size
        {
            get { return _size; }
            set { _size = value; }
        }
    }


    public class Beagle : Dog
    {
        private Size _size;
 
        public override Size size
        {
            get
            {
                return _size;
            }
            set
            {
                _size = size;
            }
        }
    }
 

Did I miss any C# variable types? Let me know what you think about this C# variables quick start guide!
0 Comments

Your comment will be posted after it is approved.


Leave a Reply.

    ​Author

    Picture
    The posts on this site are written and maintained by Jim Lynch. About Jim...
    Picture
    Follow @JimLynchCodes
    Follow @JimLynchCodes

    Categories

    All
    Actionscript 3
    Angular
    AngularJS
    Automated Testing
    AWS Lambda
    Behavior Driven Development
    Blockchain
    Blogging
    Business Building
    C#
    C / C++
    ClojureScript / Clojure
    Coding
    Community Service
    CS Philosophy
    Css / Scss
    Dev Ops
    Firebase
    Fitness
    Flash
    Front End
    Functional Programming
    Git
    Go Lang
    Haskell
    Illustrations
    Investing
    Java
    Javascript
    Lean
    Life
    Linux
    Logic Pro
    Music
    Node.js
    Planning
    Productivity
    Professionalism
    Python
    React
    Redux / Ngrx
    Refactoring
    Reusable Components
    Rust
    Security
    Serverless
    Shell Scripting
    Swift
    Test Driven Development
    Things
    TypeScript
    Useful Sites
    Useful Tools
    Video
    Website Development
    WebStorm
    Writing

    Archives

    March 2023
    August 2021
    February 2021
    January 2021
    October 2020
    September 2020
    May 2020
    April 2020
    February 2020
    January 2020
    December 2019
    October 2019
    September 2019
    August 2019
    July 2019
    June 2019
    May 2019
    April 2019
    March 2019
    February 2019
    January 2019
    December 2018
    November 2018
    October 2018
    September 2018
    August 2018
    June 2018
    May 2018
    April 2018
    March 2018
    February 2018
    January 2018
    December 2017
    November 2017
    October 2017
    September 2017
    August 2017
    July 2017
    May 2017
    April 2017
    March 2017
    February 2017
    January 2017
    December 2016
    November 2016
    October 2016
    September 2016
    August 2016
    July 2016
    June 2016
    May 2016
    April 2016
    March 2016
    February 2016
    January 2016
    December 2015
    November 2015
    October 2015

    RSS Feed

  • Blog
  • About Jim
JimLynchCodes © 2023