Learn ASP.NET MVC & Entity Framework

Step-by-Step tutorials on ASP.NET MVC and Entity Framework for Beginners

Important C# Topics to Know Before Learning ASP.NET MVC (Beginners/Professionals)

| Comments

In this post, we will learn about the important C# topics that every developer should know before learning ASP.NET MVC.

Note: You can practice this tutorial on any edition of Visual Studio like Visual Studio Pro, Enterprise or even Community edition.

Important C# topics you should know

  • Implicitly-Typed variables
  • Auto-implemented properties
  • Extension methods
  • Anonymous types and methods
  • Delegates
  • Lambda expressions

Implicitly-Typed variables

Microsoft introduced the implicitly-typed local variable var with C# 3.0.

  • var is an implicitly-typed variable
  • Implicit typing applies only to local variables in a method scope
  • It is illegal to use var to define return values and parameters.
  • Local variables declared with var must be assigned an initial value at the exact time of declaration and cannot be assigned the initial value of null
  • var can be used in a for loop, foreach loop, using statement, anonymous type, and LINQ queries.
  • When you use a var variable, the compiler will automatically/automagically infer the underlying data type based on the initial value provided at the time of declaration.
  • var i = 12 here i will be an int
  • var name = "Abhishek" here name will be a string
  • var is very useful to write LINQ queries that return dynamically created result sets. In a LINQ query, implicit typing is extremely beneficial, as the programmer doesn’t have to explicitly define the type that a query may return, which in some cases would be literally impossible to do.
// valid implicit-typed variable 
var name = "Abhishek Luv";
// Invalid implicit-typed variable 
var name;
name = "Abhishek Luv";
// Using implicit-typed variable in a LINQ query

List < int > numbers = new List < int > ();

numbers.Add(12);
numbers.Add(25);
numbers.Add(78);
numbers.Add(-34);
numbers.Add(-89);

// Linq query ordering the orders of the numbers

var queryResult = from number in numbers
orderby numbers descending
select number;

Properties

  • Properties are used to encapsulate data by using the get (accessor) and set (mutator).
  • Properties can be static or non-static, read-only, write-only or read-write.
  • Properties might look like a field, but they are more closely related to methods; property accessors get converted into methods during the compilation process.
  • Properties in C# provide the ability to protect a field by reading and writing to it through special methods called accessors and mutators.
  • Properties declared as public with the same data type as the field they are going to protect, followed by the name of the property and a code block that defines the get and set accessors.
  • Properties allow the programmer to validate the data before allowing a change.
public class Properties {
 // Old-way of declaring properties

 private int _number; // the private field 

 // Number is a property that allows to get and set the value for the `_number ` private field outside the `Properties` class.
 public int Number {
  get {
   return _number;
  }
  set {
   _number = value;
  }

  public void ShowNumber() {
   Console.WriteLine($ "The number is {_number}");
  }
 }
 

Auto-Implemented Properties

  • When a programmer is building a class that has tons of properties to encapsulate data, multiple class files might end up having a lot of private fields and its associated public properties.
  • Say hello to Auto-implemented properties.
  • With Auto-implemented properties, there is no need to create a private field
  • With Auto-implemented properties, there is no need to write extra property code
  • Just write a property with get and set accessor
  • The compiler will automatically create a private field for the properties we create which are Auto-implemented properties
  • When declaring an automatic property, it compulsory to define both the read and write functionality using get and set accessor.
  • Unlike traditional C# properties, it is not possible to build read-only or write-only automatic properties.
public class Properties {

 // Auto-implemented properties

 public string Name {
  get;
  set;
 }
}

In the above code, Name property is an Auto-implemented property and behind the scenes, the compiler will create a private backing field just like this _name. The name of the auto-generated private backing field is not visible within our C# code base. The only way to see it is to make use of a tool such as ildasm.exe.

public class Program {
 static void Main(string[] args) {
  Properties prop = new Properties();
  prop.Number = 123;
  prop.ShowNumber();

  prop.Name = "Abhishek Luv";
  Console.WriteLine(prop.Name);
 }
}

Extension Methods

An Extension method is a static method that must be contained within a static non-generic class.

Extension methods provide a means by which functionality can be added to a class without using the normal inheritance mechanism. We can extend a class without creating a derived class by creating a separate type whose methods can be called as if they belonged to the original type.

public static class ExtensionMethods {
 public static int ToInt(this string str) {
  return int.Parse(str);
 }

 public static int Divide(this int a, int b) {
  return a / b;
 }

 public static string ReverseText(this string str) {
  StringBuilder sb = new StringBuilder();

  for (var i = str.Length - 1; i >= 0; i--) {
   sb.Append(str[i]);
  }

  return sb.ToString();
 }
}
class Program {
 static void Main(string[] args) {
  string value = "123";

  int number = value.ToInt();

  Console.WriteLine(number);

  // Divide demo

  int value1 = 10;

  int result = value1.Divide(2);
  Console.WriteLine(result);

  string name = "vul";

  Console.WriteLine(name.ReverseText());
 }

}

Anonymous Types

In object-oriented languages (such as C#), it is common to define small classes that will be used only once. During compilation, the compiler will create a class with a unique name something like <>f__AnonymousType0.

In the below shown code, myDetails is an Anonymous Type i.e. without any name. When you want to use a class only once within your code then you can create an Anonymous Type.

class AnonymousDemo {
 static void Main(string[] args) {
  var myDetails = new {
   Name = "Abhishek Luv", Age = 28, Address = "Mumbai"
  };

  Console.WriteLine(myDetails.GetType());
  Console.WriteLine(myDetails.Name);
 }
}

Anonymous Methods

In situations where it is not convenient or necessary to create a named function or method. An anonymous method is one way to create an unnamed block of code that is associated with a specific delegate instance.

In the below given code, the delegate keyword is used to create an Anonymous Method that points to the DoThisTask delegate.

public delegate double DoThisTask(int value1, int value2);
public class AnonymousMethodDemo {
 static void Main() {
  DoThisTask addition = delegate(int a, int b) {
   Console.WriteLine("Addition");
   return a + b;
  };

  Console.WriteLine(addition(6, 3));
 }
}

Delegates

A function can have one or more parameters of different data types, but what if you want to pass a function itself as a parameter?

How does C# handle the callback functions or event handler?

The answer is - delegate.

A delegate is like a pointer to a function. It is a reference type and it holds the reference of a method. All the delegates are implicitly derived from System.Delegate class.

A Delegate is a type that represents references to methods with a particular parameter list and return type. when you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

Delegates are used to pass methods as arguments to other methods. They are c++ pointers but are typesafe.

A delegate is an object that can refer to a method. A delegate can be used to call any method that agrees with its signature and return type.

Invoking Delegate

The delegate can be invoked like a method because it is a reference to a method. Invoking a delegate will, in turn, invoke a method which it referred to. The delegate can be invoked by two ways: using () operator or using the Invoke() method of delegate

Delegate as a parameter

A method can have a parameter of a delegate type and can invoke the delegate parameter.

Multicasting

Multicasting is the ability to create an invocation list or chain, of methods that will be automatically called when a delegate is invoked.

The delegate can point to multiple methods. A delegate that points multiple methods is called a multicast delegate. The “+” operator adds a function to the delegate object and the “-” operator removes an existing function from a delegate object.

public delegate double CompleteTask(int value1, int value2);
public class MyDelegate {
 public static double Addition(int a, int b) {
  Console.WriteLine("Addition");
  return (a + b);
 }

 public static double Subtraction(int a, int b) {
  Console.WriteLine("Subtraction");
  return (a - b);
 }

 // no-static methods
 public double Divide(int a, int b) {
  Console.WriteLine("Division");
  return (a / b);
 }
}


static void Main() {
 CompleteTask doThis;
 CompleteTask doThis = MyDelegate.Addition;
 Console.WriteLine(doThis(5, 2));

 // for instance methods

 MyDelegate obj = new MyDelegate();

 doThis = obj.Divide;
 Console.WriteLine(doThis(6, 2));


 Console.WriteLine("-------------------");

 // multi-cast delegates

 //doThis = MyDelegate.Addition;
 //doThis += MyDelegate.Subtraction;
 //doThis += obj.Divide;


 //Console.WriteLine(doThis(12, 2));
 // value returned by the last method in the list becomes the return value of the entire delegate invocation.
}

Lambda Expressions :

Lambda Expression is an anonymous function that you can use to create delegates or expressions tree types. you can write local functions that can be passed as arguments or returned as the value of function calls.

  • Lambda expressions are particularly helpful for writing LINQ query expressions.
  • Lambda expressions are used in method-based LINQ queries as arguments.
  • Lambda expression is the second way that an anonymous function can be created.

param => expression(expression lambda), (param-list) => expression

On the left, the input parameter(or parameters) is specified. on the right is the lambda body. the => operator is sometimes called as “goes” or “becomes.”

If the lambda body consists of a block of statements enclosed by braces, then a statement lambda is being created.

public delegate int Calculate(int value1, int value2);
public delegate double SquareRoot(int value);

public class LambdaExpressionDemo {
 static void Main() {
  SquareRoot sqrt = x => Math.Sqrt(x);
  Console.WriteLine(sqrt(144));

  Calculate cal = (x, y) => (x * y);
  Console.WriteLine(cal(12, 12));

  Calculate cal;
  cal = (x, y) => {
   Console.WriteLine("If method has multiple liness just used curly braces");
   int result = x * y;
   return result;
  };

  Console.WriteLine(cal(10, 20));

 }
}

Next Post: In the next post, we will learn about the ASP.NET MVC application folder structure.

Comments