C# Notes

1. VS Shortcuts
2. Requirements
3. Classes and Objects
4. Constructors
5. Classes and Variables
6. Reference Types
7. Access Modifiers
8. Statics
9. Calculating Statistics
10. Computation
11. Assemblies
12. Browsing Assemblies
13. Referencing Assemblies
14. Unit Testing
15. Types
16. Reference Types
17. Value Types
18. struct and enum
19. Passing Parameters
20. ref and out
21. Immutability
22. Arrays
23. Methods, Fields, Events, and Properties
24. Properties
25. Events
26. Delegates

----Shortcuts----
Tab twice after typing the following:
ctor - creates a constructor
prop - creates a property
cw - creates a Console.WriteLine()
testm - creates a [TestMethod]

----Requirements----

We need an electronic grade book to read the scores of an individual student
and then compute some simple statistics from the scores.

The grades are entered as floating point numbers (float) from 0 to 100, and the statistics should show us
the highest grade, the lowest grade, and the average grade.

----Classes and Objects----

GradeBook class -

Class members define:
1. State
2. Behavior

GradeBook State
1. The grades for a user

GradeBook Behavior
1. Add a new grade
2. Calculate statistics

create objects with class (like a cookie cutter)
Objects are allocated into memory
new keyword

----Passing Parameters----

Methods pass parameters "by value" by default. You always pass a copy of the variable unless you use
special keywords. (not good practice)

For reference types, you are passing a copy of a reference.

public void DoWork(GradeBook book) {
   book.Name = "Grades";
}

The calling code and the method will have pointers to the exact same object.

----ref and out----

These are rare. Passing variable by reference, instead of by value.

----Immutability---

Cannot change the value of 4. Cannot change the value of August 9th, 2002.

DateTime date = new DateTime(2002, 8, 11);
date.AddDays(1);

This won't work! Can change value but can't add 1 days to original value. Even though
datetime and strings are reference types, they work as value types. Have to assign a new value to
the original variable in order to change it.

This will work:

DateTime date = new DateTime(2015, 1, 1);
date = date.AddDays(1);

Because DateTime assigns the new value to the variable, date.

----Arrays----

Manage a collection of variables

Use a List or Collection because arrays have a fixed size.
Both List and Arrays are 0 indexed.

Arrays:

  • Fixed size
  • Index starts at 0.

Arrays are reference types. Even though you are storing value types (ints, floats, etc.) in the array, the variables are pointing to 
the same.

[TestClass]
    public class TypeTests
    {
        [TestMethod]
        public void UsingArrays()
        {
            float[] grades;
            grades = new float[3];

            AddGrades(grades);
            Assert.AreEqual(89.1f, grades[1]);
        }

        private void AddGrades(float[] grades)
        {
            //grades = new float[5]; //this will fail, pointing to a new array
            grades[1] = 89.1f;
        }

----Methods, Fields, Events, and Properties----

  • New class members introduced
  • Methods define behavior
  • Every method has a return type - void if no value returned
  • Every method has zero or more parameters
  • Use params keyword to accept a variable number of parameters
  • Every method has a signature
    • Name of method + parameters
    • You can have methods with same name with different parameters, the signatures have to be unique. 
      This is called method overloading.
  • The return type is NOT part of the method signature.
public void WriteAsBytes(int value)
        {
            byte[] bytes = BitConverter.GetBytes(value);

            foreach(byte b in bytes)
            {
                Console.Write("0x{0:X2} ", b);
            }
        }
class Program
    {
        static void Main(string[] args)
        {
            GradeBook book = new GradeBook();
            book.AddGrade(91);
            book.AddGrade(89.5f);
            book.AddGrade(75);

            GradeStatistics stats = book.ComputeStatistics();
            WriteResult("Average", stats.AverageGrade);
            WriteResult("Highest", (int)stats.HighestGrade); //this is a type coercion or type cast. convert float into an int.
            WriteResult("Lowest", stats.LowestGrade);
            //book2.grades Can't access private members outside of class
        }
        static void WriteResult(string description, int result)
        {
            Console.WriteLine(description + ": " + result);
        }
        static void WriteResult(string description, float result)
        {
            Console.WriteLine("{0}: {1}", description, result);
        }
    }

OR with C#6, you can use string interpolation like this:

static void WriteResult(string description, float result)
        {
            Console.WriteLine($"{description}: {result:F2}"); //no longer need to pass description and result as parameters
        }

----Fields----

Fields are variables of a class, typically something you want to protect.
Naming convention : underscore

public class Animal
        {
            private readonly string _name;
            public Animal(string name)
            {
                _name = name;
            }
        }

Notice the readonly keyword, you can only set the name value in the constructor method. 
C# will give you compiler error if set in any other method for this class.

----Properties----

Properties are similar to fields because it controls state and the data associated with an object.

But unlike a field, a property has a special syntax that can be used to control what happens when someone
reads the data or writes the data. These are known as the get and set accessors. These accessors can contain code.
Example:

private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    _name = value;
                }
            }
        }

auto-implemented property

public string Name { get; set; }

behind the scenes, C#will create the field and implement the property.
Some parts of the .Net framework and C# treat fields and properties differently, particularly when
you are doing serialization (taking in an object and serializing it into XML or JSON or saving it to a database).
Data-binding features typically don't pass to a view.

What is we want to protect against Name getting set to null?

Need to change to custom field and property, see below:

public string Name
        {
            get { return _name; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    _name = value;
                }
            }
        }
        private string _name;

----Events----

Allows a class to send notifications to other classes or objects
Example: Button click, track a directory, timer expires, refresh data, etc.
The button publishes the event, the subscriber processes the event (reacts to it)

This is all done through the magic of delegates.

----Delegates----

Imagine you want to declare a variable that references a method. You want to declare a variable and point the variable to a method.
That means you will have a variable that encapsulates executable code. You can invoke the variable just like you would a method (by using 
parenthesis and optionally passing some parameters).

In order for this to work, you need to create a delegate type. A delegate is a type that references methods.

public delegate void Writer (string message);

public class Logger
        {
            public void WriteMessage(String message)
            {
                Console.WriteLine(message);
            }
        }
Logger logger = new Logger();
Writer writer = new Writer(Logger.WriteMessage);
writer("Success!!");

like C++ or Javascript, it is a variable that points to a function.

Somewhere in the application, it needs to know when Name property gets updated. Perfect scenario for delegates.

Your class will know when the button is clicked, but how will your class announce to the rest of the world that the button
is clicked?

Create a delegate to subscribe to an event.
set a property in the object you want to subscribe to the event.
Invoke the delegate event variable (method)
Create a method that invokes some code when the event happens in separate class.
Set the instance of the object.delegate property to new DelegateType(name of the method);
Example: 

In NameChangedDelegate.cs:

public delegate void NameChangedDelegate(object sender, NameChangedEventArgs args);

In GradeBook.cs,

public string Name
        {
            get { return _name; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if(_name != value)
                    {
                        NameChangedEventArgs args = new NameChangedEventArgs();
                        args.ExistingName = _name;
                        args.NewName = value;
                        //this represents the object you are working in, GradeBook
                        //see the delegate and event declared below, a field in the GradeBook, takes two args
                        NameChanged(this, args);
                       
                        //NameChanged(_name, value);
                    }
                    _name = value;
                }
            }
        }
        public event NameChangedDelegate NameChanged;

In Program.cs:

static void Main(string[] args)
{
   book.NameChanged += new NameChangedDelegate(OnNameChanged);
}
static void OnNameChanged(object sender, NameChangedEventArgs args)
{
   Console.WriteLine($"Grade book changing name from {args.ExistingName} to {args.NewName}");
}





Add comment

Loading