Home » C# concepts

C# concepts


LINQ : It stands for language integrated query, which allows us to query any type of datastore like sql server, xml docs, objects in memory (arrays, lists) etc. There are three different ways to write Linq query in c#.                                                      

a) Query Syntax: Syntax looks similar to sql query. Lets try to understand with a simple example.                                 

List<int> num= new List<int>() { 6, 7, 8, 9, 10,11};
IEnumerable query = from a in numbers 
                    where a< 11 && a< 7
                    select a;    
Here the result will be stored as query object and mostly as IEnumerable<T> or IQueryable<T>.



Nullable Types: All value types like int,  are non nullable by default.
ex: int k = null; This gives compiler error

If there is a requirement to have a null value stored in this value type, then we have following ways to do it.
1) int ? k = null; 
2) Nullable<int> k = null;


Parse() vs TryParse()
These two methods are used to convert a number which is in string format to an integer.
ex for Parse(): string myNum = "118";
                int num = int.Parse(myNum);

ex for TryParse(): string myNum ="118ABCD"; 
                   int num = int.Parse(myNum); This will display format exception. To overcome this, we make use of TryParse()
                   
                   string myNum = "118ABCD";
                   int res = 0;
                   int.TryParse(myNum, out res); // This method will return boolean value, true if conversion is successfull else it will return false. 

Implicit conversion vs Explicit conversion

Implicit conversion is performed by compiler implicitly when there is no loss of information or no overflow exception. This occurs in the case of conversions from smaller datatype to larger datatype or conversions from child classes to parent.

Explicit conversion has to be performed explicitly either using cast operator or Convert class. When we try to convert larger type like float to smaller type like int, there will be loss of fractional part of float. 

If you use type cast operator, it will not show any exception for failed conversion where as Convert class will show exception for the failed conversion.