#804 – Tradeoffs when Using the var Keyword

You’d most often use the var keyword, indicating an implicit type, in the following situations:

  • For anonymous types  (var is required)
  • As the type of the result of a LINQ expression
  • To avoid duplicating a long type name

You should end up using var if its use is required (for anonymous types) or if using var improves the readability of your code.

You must be careful, however, in using var to simplify your code.  In many cases, while its use may make writing your code easier, the omission of a type can make the code less readable, because the person later reading the code may need to first determine the variable’s type before being able to use it.

A good rule of thumb is to use strongly typed variables by default and only use var when it is necessary.

Advertisements

#803 – Situations When You Might Use the var Keyword

The var keyword allows you to avoid entering the full type of a variable, letting the compiler infer the type.  The variable is still strongly-typed, i.e. the type is known at compile time.

There is debate about when you should use var.  It’s use ends up dictated by coding style guidelines or personal preference.

You must use var when dealing with anonymous types because the compiler generates only an internal type name.

var myDog = new { Name = "Kirby", Age = 14 };

You might  use var when using LINQ, when the exact type of the query result is not apparent.

            var someDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name + "(" + aDog.Nickname + ")";

You might also use var to avoid having to repeat a type name that is already present in an expression.

            var dogs = new List<Dog>();

#802 – A Method Might Have No Parameters

You can pass one or more data values to a method using parameters.  A parameter in a method is just a variable, usable only within that method, that refers to a piece of data passed into the method.

If the method that you are writing requires no data to be passed in, you can omit all parameters.  You include an empty pair of parentheses after the method name, to indicate that the method has no parameters.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // All data that we need is passed into constructor
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        // Bark is a method that has no parameters
        public void Bark()
        {
            Console.WriteLine(string.Format("{0} : WOOF !", Name));
        }
    }

#801 – An Example of a Simple Immutable Class

You sometimes want to make a class immutable–meaning that you can’t change any instance data in an object after it is created.

Below is an example of a simple class, created using the guidelines for creating an immutable class.

    public class ImmutableDog
    {
        // All properties are read-only
        public string Name { get; private set; }
        public int Age { get; private set; }

        // Return copy of any mutable data
        //   (assuming that DogCollar is mutable)
        private DogCollar collar;
        public DogCollar Collar
        {
            get { return (DogCollar)collar.Clone(); }

            private set
            {
                if (collar != value)
                    collar = value;
            }
        }

        // All data that we need is passed into constructor
        public ImmutableDog(string name, int age, DogCollar collar)
        {
            Name = name;
            Age = age;

            // Make copy of any mutable data passed in
            Collar = (DogCollar)collar.Clone();
        }

        // Methods don't change instance data
        public void DoSomething()
        {
            Console.WriteLine(string.Format("Hi, I'm {0}, aged {1}", Name, Age));
        }
    }

#800 – A Property in an Interface May Include One or Two Accessors

Defining a property in an interface, you can define one or both of the property’s accessors.

    public interface IDogInfo
    {
        int CollarSize { get; set; }
        string Name { get; }
        string SecretName { set; }
    }

When you implement an interface, if a property in the interface has both accessors, you must implement both accessors, and both must be public (you set an access modifier of public on the entire property).

If a property in the interface includes only one accessor, you must implement that accessor, but you can optionally also implement the other accessor.

    public class Dog : IDogInfo
    {
        public int CollarSize { get; set; }

        // IDogInfo has just get
        public string Name
        {
            get { return "NotImpl"; }
        }

        // IDogInfo has just set, but we add a get
        public string SecretName { protected get; set; }
    }

#799 – Interface Members Are Implicitly Public

When you declare an interface, you cannot use access modifiers on interface’s member.  An interface makes a collection of members available to code that accesses a class implementing that interface.  So it makes sense that the interface members are public.

    public interface IBark
    {
        int BarkCount { get; set; }
        void Bark(string woofSound, int count);
    }

When you implement an interface, you must mark the interface members as public.

    public class Dog : IBark
    {
        public int BarkCount { get; set; }

        public void Bark(string woofSound, int count)
        {
            for (int i = 1; i <= count; i++)
                Console.WriteLine(woofSound);
        }
    }

If you implement the interface explicitly, the members are implicitly public and you cannot mark them with access modifiers.

        int IBark.BarkCount { get; set; }

        void IBark.Bark(string woofSound, int count)
        {
            for (int i = 1; i <= count; i++)
                Console.WriteLine(woofSound);
        }

#798 – You Can’t Override Accessors that Are Not Accessible

When you override a virtual property in a child class, you must replicate the accessibility of the accessors in the parent’s class.

However, if one of the accessors has been made inaccessible to the child class, you’ll be able to override the property itself, but not that accessor.

In the example below, we override the Description property, including the get accessor.  However, if we try to include the set accessor in the overridden property, we get a compile-time error because the set accessor is not accessible to the child class.

    public class Animal
    {
        protected string description;
        public virtual string Description
        {
            get { return string.Format("Animal: {0}",description); }

            private set
            {
                if (value != description)
                    description = value;
            }
        }
    }
    public class Dog : Animal
    {
        public override string Description
        {
            get { return string.Format("Dog: {0}", description); }

            private set
            {
                if (value != description)
                    description = value;
            }
        }
    }

798-001