Showing posts with label c-sharp. Show all posts
Showing posts with label c-sharp. Show all posts

Wednesday, July 17, 2019

What is Yield in C# and when to use it

Yield is a keyword in C# which is not understood properly by many people. So what is yield? When you specify yield you'll only get next element from an iterator. Means you'll use yield with an iterator. This removes the need of an extra class or logic which holds the collection.

Simple example of usage of yield keyword



In the above example you are returning the results list. Which is an extra parameter. You can remove this by introducing yield keyword to temporary hold the value in each iteration.

By using yield you don't have to iterate the complete collection. You can breakaway from the collection using break statement. 

Good use cases of yield is when converting DataTable to IEnumerable<T>. Also see when not to use yield.


Thursday, December 22, 2016

How Default Constructor Works in C#

Whenever a class or struct is created, its constructor will be called. Constructors enables developer to set default values and limit initialization. 

If the constructor is not provided, C# will instantiate default constructor and will assign default values to the member variables. Since value types cannot be null, they will be assign with default values while, Since reference types are null by default they will be assigned with null (Note that regardless of been value or reference type, local variables are not automatically initialized). 

Here .ctor is the shorthand for constructor called in IL (Intermediate Language). As you can see from the above screenshot, you can use free disassembler like ILSpy to view disassembled code.  

If you provide a parameterized constructor, the empty constructor will not be generated.



The purpose of user defining a parameterized constructor is to add some logic when initializing the class, if the compiler automatically adds a empty constructor, users can bypass the some logic in parameterized constructor class. That's why empty constructor is not generated.

Constructor can use base keyword to call the constructor of the base class. (for further details, see Using constructors).

If you try to invoke base default constructor and haven't specified it in the base class you will get 'does not contain a constructor that takes 0 arguments' error.

Static classes can have static constructors to initialize static data. It does not have parameters, and the constructor cannot be called directly. It'll be called automatically. Basically user does not have any control over it. (DotnetPerls)
  
Structs can also have constructors (link2). 

Private constructor is a special type of constructor. It is generally used in classes which contain static members only. Static constructor is used to initialize any static data, or to perform any action which should be performed only once.

Monday, December 29, 2014

C# - Classes and Structs

Classes and structs encapsulates set of data and behaviors into a logical unit. A class is a reference type while struct is of value type. When a struct is assigned to a new variable it is copied. Struct is like a light-weight class. (Read)


Note: the new operator is used to create and invoke objects. The new operator doesn't mean it is a reference type. It says the type has a constructor. All value and reference types has constructors at least the default one. (SO).

int i = new int(); equals to
int A = new int(); or int A = default(int);

Encapsulation defines how accessible the members of the classes are to the outside of the class. Class can have fields, constants, properties, methods, constructors, destructors, events, indexers, operators as well as nested types. (See Class members article)

When defining a struct if you're adding a parameterized constructor, you must initialize all fields in that (Source). Also it is not a good practice to use mutable structs. See examples of mutable structs. 

Inheritance : Classes support inheritance. A class can derive from another class (base class). Structs does not support inheritance because it is of value type. Classes can be declared as abstract meaning, one or more methods have no implementation. Classes and structs can inherit multiple interfaces. 
See : Why structs cannot be inherited, Why structs needs to be boxed, 

Generic Types : Classes and structs can be defined with one or more type parameters.

Static types : Classes can be declared as static while structs cannot. A static class can only contain static members and cannot be instantiated with new keyword. Both classes and structs can contain static members

Nested types : class and struct can be nested within another class or struct. (See Nested Types - MSDN)

Partial classes : You can also define a class in two files using partial. 

Object initializers : You can instantiate class or struct object without explicitly calling the constructor.  (MSDN)

Anonymous types : When it is not necessary to create named classes, you can use anonymous types. (See Anonymous Types in C# Programming guide)

var msg = new { Id = 108, Message = "Hello" };

Anonymous types are typically used in select clause of query expressions (LINQ). Anonymous type can contain  one or more public read-only fields. It cannot contain anything else (such as methods, event handlers etc.). 

Extension methods : You can extend a class without creating a derived class by creating separate types using extension methods.

Implicitly typed local variables : You can use these variables to instruct the compiler to determine correct type at runtime. (See implicitly typed local variables)


Resources
https://roslyn.codeplex.com/discussions/568824
http://programmers.stackexchange.com/questions/92339/when-do-you-use-a-struct-instead-of-a-class

Thursday, August 21, 2014

Abstract in C#

In this article, we'll look at what abstract in C# is. Also we'll look at 
when and how you can use it to get its benefits.


In C# abstract modifier indicates that the thing being modified has a missing or incomplete implementation. This modifier can be used with classes, methods, properties, indexers and events. 

Abstract classes can contain both abstract and non-abstract members. Abstract member cannot exist outside an abstract class. You can instantiate abstract class by making a concrete class deriving from it (An instance of a derived class is also a instance of its base class). 

Also you can't create abstract constructor because abstract means you must override it in any non-abstract child class. But you can have non-abstract constructors. You can't override a constructor. You can't create sealed abstract classes. 

You cannot have non-abstract method signature inside abstract class. For non-abstract methods you must provide implementation (link). You cannot have private virtual or abstract members inside a abstract class. But You can have non-abstract private methods inside abstract classes.



Saturday, July 26, 2014

Hidden Secrets of Interfaces in .NET C#

Interface contains definitions for a group of related functionalties that a class or a struct can implement. Interface in C# is similar to an abstract class in which all methods are abstract (Why C# interface methods not declared as abstract). 

Interface can contain methods, properties, events, indexers but it can't contain constants, fields (why interface can't have fields), operators, instance constructors or types. Interface members are automatically public and cannot be static. (interfaces in MSDN)

When a class or struct implements an interface, it must provide an implementation for all the members that interface defines. If you implement an interface method in a deriving class it must be public. When a base list contains base class and interfaces, base class must come first in the list. 

Methods in interfaces can have optional parameters. But they are not enforced in implementing classes. 

Any class or struct that implements IEquatable<T> interface must contain definition for an Equals method. Also note that Reference types doesn't benefit much when using IEquatable.

Importance of an interface
Covered in SO, SO, Here 

An interface can inherit from one or more base interfaces. See Composition over Inheritance.

Explicit interface implementation 

Problem : Class implements 2 interfaces has a member with same signature
Solution : Explicit interface implementation



Friday, July 25, 2014

How to Asynchronous Programming in C#

async and await are the main keywords in asynchronous programming. You can use asynchronous with things such as downloads, uploads etc.


Below example shows you how to get a specific Http Header asynchronously.

  • Name of async method by convention ends with async. 
  • Return type is one of the following,
    • Task<TResult>
    • Task
    • void
  • Method has at least one await expression
Resources

https://msdn.microsoft.com/en-us/library/hh191443.aspx

Wednesday, July 9, 2014

Covariance and Contravariance in Generics

Covariance

Enables you to use more specific type than the type originally specified.

IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;

Contravariance

Enables you to use more generic type than the type originally specified.

Action<Base> b = (target) => { Console.WriteLine(target.GetType().Name); };
Action<Derived> d = b;
d(new Derived());
Examples from MSDN.


Resources
https://msdn.microsoft.com/en-us/library/ee207183.aspx
http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example

Wednesday, May 7, 2014

Understanding IEnumerable and IQueryable in C#

IEnumerable<T> is the base interface for collections in System.Collections.Generic namespace. IEnumerable<T> exposes the enumerator which supports iteration over a collection of a specified type. For non-generic types .NET has another interface called IEnumerable. See the difference between IEnumerable<T> and IEnumerable. IEnumerable<T> has a single method GetEnumerator which you must implement when implementing the IEnumerable<T> interface. This returns a IEnumerator<T> object.



IQueryable<T> provides functionality to evaluate queries against a data source. This exists in System.Linq namespace. This inherits IEnumerable<T> interface thereby if it represents an query it can be enumerated. Enumeration forces associated expression tree to be executed.




Difference between IQueryable<T> and IEnumerable<T>
Both will give the ability for deferred execution but IQuerayable allows you to LINQ to SQL while IEnumerable does not. IEnumerable only allows LINQ to Object. IQueryable if possible will execute on database. 

AsEnumerable
Allows you to cast a specific type to its IEnumerable equivalent. In LINQ you can use this to run part of the query in SQL and the other part in memory as LINQ to Objects. One reason because when execute in memory we have more methods to work with than in database. (Ref)


AsQueryable
Converts IEnumerable to an IQueryable.

When exposing any of these interfaces to a client, the developer should design the API such that only the required details are exposed to the outside. 
Source - Stackoverflow
Also see questions for IEnumerable under stackoverflow

IEnumerable<T> has lot of extension methods. Check them here.

Provides a set of static methods for querying objects that implements IEnumerable<T>. This can be found under System.Linq namespace.

Enumerable.Empty<TResult> : 
Returns an empty IEnumerable<T>. 

Wednesday, January 1, 2014

Overloading, Overriding and hiding in C#

Overloading and overriding are concepts in polymorphism.

Overloading

Use overloading when multiple methods has same purpose but there is more than one way to do. Overloaded methods have different parameters.

E.g:
void ReadXml(string fileName) {  }
void ReadXml(Stream strm) {  }

An alternative to method overloading is to use optional parameters.
public void Foo(int x = 1)

Also use named parameters for readability.
t.Foo(x: 12);

You can also use params keyword to have unlimited no. of arguments of a specified type like below,\

        public int Foo(params int[] x)
        {
            return x.Sum();
        }

call it like,
t.Foo(1, 2, 3);

Overriding

Concept in which subclasses provides specific implementation of a method provided by the super class.

    class A
    {
        public virtual string Method()
        {
            return "A";
        }
    }

    class B : A
    {
        public override string Method()
        {
            return "B";
        }
    }

    class C : A
    {
        public string Method()
        {
            return "C";
        }
    }

            A a = new A();
            Console.WriteLine(a.Method()); //A

            A a2 = new B();
            Console.WriteLine(a2.Method()); //B

            B b = new B();
            Console.WriteLine(b.Method()); //B

            C c = new C();
            Console.WriteLine(c.Method()); //C

In the last example, c.Method() hides a.Method(). Therefore it gives a warning. To remove the warning append new in front of  public string Method()

http://stackoverflow.com/questions/3838553/overriding-vs-method-hiding

http://stackoverflow.com/questions/25008021/why-does-this-c-sharp-code-return-what-it-does/25008171#25008171

Using IComparer, Comparer and IComparer in C#

IComparer

IComparer interface exposes a method to compare two objects. This interface comes under System.Collections namespace. You can use this with Array.Sort() method. To use with Generic classes you must use IComparer<T> interface.

You can check the example in MSDN documentation to see how to use IComparer with an Array.

IComparer<T>

This interface comes under System.Collections.Generic namespace. This is similar to IComparer. This interface is used with List<T>.Sort and List<T>.BinarySearch methods and provides a way to customize the sort order of a collection.

The StringComparer class implements this for String. 

IEqualityComparer<T>

Comparer<T>

This interface provides a base class for implementations of the IComparer<T> interface. 

It is recommended to use Comparer<T> instead of IComparer<T> 


Resources

Using IComparable in C#

In case you want to compare 2 objects for sorting purpose you can use this interface. IComparable defines a type specific comparison method. Value types and classes can implement this interface. 

Lets say you have a list of people and you want to sort it by age. You'll use Sort method comes with the list. Usually the Sort() method will use default comparer for the type specified by the generic argument, Here default comparer for Person. 


But it'll throw an error when trying to sort because Person does not have a comparer and it does not know how to sort them. Therefore you need to implement IComparable and its CompareTo method like below.


Now the sorting will happen successfully. Note that implementation of CompareTo(Object) must return a Int32. All numeric types such as Int32 and Double implements IComparable.


Resources

Overview of .NET Framework


Above diagram shows a high level overview of .NET framework

Managed code vs Un-managed code
Managed code : code that is executed directly by the CLR. 

Un-managed code : Code that is directly executed by the operating system.

Covariance and contra-variance
http://www.indiabix.com/technical/dotnet/dot-net-framework/5 
https://www.google.lk/search?q=covariance%20and%20contravariance


Resources
http://msdn.microsoft.com/en-us/library/vstudio/zw4w595w%28v=vs.110%29.aspx


Image credit : codeguru

C# - Project Structure and MSBuild

Project structure for MVC Application
This is a typical project structure you'll get when you create a MVC application from Visual Studio 2013.

App_Start has Configurations to initialize from Global.asax

Content has styling files and Scripts folder has all the Script files (JavaScript etc.)

Views folder has Views in MVC with a separate Web.Config file for views.

packages.config is the file for Nuget packages. see SO.

Web.config file has all configuration information about the application.

MSDN - MVC Framework and Application Structure






Project structure for Windows Forms Application


This is a sample project structure for a windows forms application (got from CodeProject). 










MSBuild (Microsoft Build Engine)

It is a build too. MSBuild does not depend on Visual Studio but Visual Studio depends on MSBuild. You can run MSBuild even from the command window.

MSBuild Project File

Is a XML file. For C# it has the extension of .csproj.

Basic elements,

Items #
Inputs into the build system, typically represents files
You can put items inside ItemGroup element

Properties #
name value pairs

Tasks

Targets

References
http://msdn.microsoft.com/en-us/library/dd393573.aspxhttp://stackoverflow.com/questions/6446361/what-does-the-csproj-file-do
http://www.asp.net/web-forms/overview/deployment/web-deployment-in-the-enterprise/understanding-the-project-file
http://www.asp.net/web-forms/overview/deployment/web-deployment-in-the-enterprise/understanding-the-build-process

Useful Interfaces in .NET

IEnumerable<T>

Exposes the enumerator which supports iteration over a collection of a specified type. This interface can be found under System.Collections.Generic namespace. 

This is the base interface for collections in Collections.Generic namespace such as  List<T>, Dictionary<TKey, TValue> etc.. For non-generic .NET has IEnumerable.

IEnumerable<T> has a single method GetEnumerator which you must implement when implementing the interface. This returns a IEnumerator<T> object.


IEnumerable 

Just like its generic version, exposes an enumerator.



IComparable


IComparer

IDisposable


IQuerable


IEqutable


IList


IDictionary

IEqutable in C#

To do object comparisons you can use Object.Equals method. But this method could behave differently than you expected. Also it will have to do a cast to Object in order to perform the equality comparison which will result in a performance drop.

IEqutable<T> defines a generalized method which a value type or a class can implement to create type specific equality comparison. It contains a single method Equals. The IEqutable<T> interface is used by Collection objects such as Dictionary, List etc. in methods like Contains, IndexOf and Remove. 

When you implement IEquatable, you should implement IEqutable.Equals as well as Object.Equals(Object) method. When you implement IEqutable.Equals, runtime will use this only if you pass object with the same type. Otherwise it'll try to use Object.Equals method.

Using with Value Types
For a value type, you should always implement IEqutable<T> and override Object.Equals(Object) for better performance. Object.Equals boxes value types and relies on reflection to compare two values for equality. See SO answer for an implementation. 

With value types you also need to overload the equality (==) and inequality (!=) operators which is important to avoid boxing and unboxing in equality checking. You can use ReferenceEquals for this.

IEqutable<T>.Equals method
Indicates whether current object is equal to another object of same type. 

When to use IEqutable<T>

We know that IEqutable<T> is used by generic collections such as Dictionary and List. The IEqutable<T> implementation will require one less cast for  these classes and will be slightly faster than object.Equals method.

Also you can have explicitness of implementing IEqutable<T>. 


Read this article from CodeProject to get a good understanding

IEqualityComparer<T>
It is an object that performs comparison of two objects of type T. IEqutable<T> is for an object so that it can compare itself with another object. (See difference)

Resources

C# - Members of a Class

A class can have following members inside it

Fields allow classes and structures to encapsulate data. A field can be given an initial value. Fields are initialized automatically before the constructor for the object instance is called. A field initializer cannot refer to other fields. 

Generally it is not recommended to use public fields. You should mark them as private and expose them via. Properties.

Properties
Is a flexible mechanism to read, write or compute value of a private field. Properties are actually special methods called accessors.

introduced in C# 3.0, Auto implemented properties make property declaration more easy. When you create a auto implemented property, compiler creates a private, anonymous backing field that can only be accessed through property's get and set accessors. To give auto implemented properties a default value you have to do it in the constructor but starting from C# 6.0 you can do it more easily.

fields, constants, properties, methods, constructors, destructors, events, indexers, operators as well as nested types
 
Using Fields vs. Properties

constants
 
methods
 
constructors
 
destructors 
 
events
 
indexers
 
operators
 
nested types

Saturday, November 9, 2013

Interesting Things on C#

Func vs Action

  • Func returns values from the delegate (LINQ .Where())
  • Action does not return anything (LINQ Foreach())

Fluent interfaces

https://www.simple-talk.com/dotnet/.net-framework/fluent-code-in-c/


Asynchronous Programming 

Using async and await 

Fluent validations


https://fluentvalidation.codeplex.com


IDisposable interface

http://stackoverflow.com/questions/6967108/is-idisposable-dispose-called-automatically
http://stackoverflow.com/questions/45036/will-the-garbage-collector-call-idisposable-dispose-for-me
Implementing IDisposable correctly


IDisposable vs Destructor (SO1, SO2)
IDisposable vs finalize (SO, MSDN)

Logging 

https://code.google.com/p/elmah/

Preprocessor Directives (link)
Provides instructions to the compiler. Used to help in conditional compilations.

Type Inference
C# used to be a strongly typed language. You need to specify the type of the variable explicitly. But from C# 3.0 type inference was introduced. with var keyword. This is very useful in LINQ and sometimes also increases  the readability of the program (See here, here and here). var is also called implicitly typed local variable.

Read more here, here (SO), MSDN, var and performance.

dynamic type 
you can use dynamic type to by-pass compile time type checking. It's type can be changed at run time hence these are resolved at run-time. dynamic type behaves like object.

dynamic can be used to make poorly designed external libraries easier to use. See here and here.

MSDN. 

Thursday, November 22, 2012

C# Tips and Tricks

For a seasoned software developer, knowing just the basics and theories of programming is going to do any good. They must also be aware of little tricks which makes development easy and fun. In this article I'll share few tips which we can use to improve our coding. (I'll be focusing on C# here.)

Null-Coalescing operator

Rather than explaining its better to show it using an example.

You can also chain these
Stackoverflow :What do ?? means in C#

yield method

using yield you can return each element one at a time for a list. (Lazy) (MSDN, SO, CodeProject easy to understand)


IEnumerable<int> Integers()

        {
            List<int> list = new List<int> { 1, 2, 3 };

            foreach (var item in list)
            {
                yield return item;
            }
        }

Extension methods

Allows you to add methods to existing types without creating new derived type. These are special kind of static method. The most common extension methods are LINQ standard query operators that add query functionality to existing System.Collections.IEnumberable and System.Collections.Generic.IEnumerable<T> types. 

You can use extension methods to extend a class or interface, but not to override them. An extension method with same name and signature as an interface or class method will never be called. At compile time extension methods always have low priority than instance methods. 

Defining extension method on Object will make the method available to all objects. This won't have any performance cost. Basically it won't get attached to each object. Rather you can call the extension method from any object. (See SO article)

I'll update this list continually. Hope this list will be useful for you. 

P.S: Find out more Hidden features of C# (SO)

image credit : blastmobilefitness

Sunday, September 30, 2012

Lambda Expressions in C#

Lambda expression is a anonymous function that you can use to create delegates or expression tree types. These are useful for writing LINQ query expressions.

Expression Lambdas

A lambda expression with a statement on right side of => operator. These are used to construct expression trees. 


Statement Lambdas

Resembles an expression lambda except that statements are enclosed in braces. 


Async Lambdas


Incorporate asynchronous processing by using async and await keywords.



Generic Delegates ##

a delegate can define its own type parameters. A code that uses generic delegate can specify type argument to create a closed constructed type, just like when instantiating or creating a generic. 


What is a method group in C# (SO)


Lambdas with Standard Query Operators

Many standard query operators have an input parameter whose type is one of Func<T,TResult> family of generic delegates. 


Type inference in Lambdas

Usually you don't have to specify the type of input parameters because compiler can infer the type based on lambda body,  the parameters delegate type etc. 


Resources
Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook