Showing posts with the label C#

if(expression) should be boolean in C#

The expression in an if statement must be enclosed in parentheses. Additionally, the expression must be a Boolean expression. In some other languages (notably C and C++), we can write an integer expression, and the compiler will silently convert the integer value to true (non-zero) or false (0)  C# does not support this behavior, and the compiler reports an error if we write such an expression. If we accidentally specify the assignment operator, =, instead of the equality test operator, ==, in an if statement, the C# compiler recognizes your mistake and refuses to compile our code. For example: int seconds;   ...   if (seconds = 59)  // compile-time error   ...   if (seconds == 59) // ok Accidental assignments were another common source of bugs in C and C++ programs, which would silently convert the value assigned (59) to a Boolean expression (with anything nonzero considered to be true), with the result that the code following the if statement would be performed eve

Data Types in C#


Using switch Statements in C#

Sometimes when we write a cascading if statement, all the if statements look similar because they all evaluate an identical expression. The only difference is that each if compares the result of the expression with a different value. For example, consider the following block of code that uses an if statement to examine the value in the day variable and work out which  day of the week it is: if (day == 0)       dayName = "Sunday";   else if (day == 1)       dayName = "Monday";   else if (day == 2)       dayName = "Tuesday";   else if (day == 3)       ...   else       dayName = "Unknown"; In these situations, often we can rewrite the cascading if statement as a switch statement to make our program more effcient and more readable. Syntax:- The syntax of a switch statement is as follows (switch, case, and default are keywords): switch ( controllingExpression )   {       case constantExpression :      

Nullable Types in C#

Nullable Types The null value is useful for initializing reference types, but null is itself a reference, and we cannot assign it to a value type. The following statement is therefore illegal in C#: int i = null; //this is illegal However, C# defines a modifer that we can use to declare that a variable is a nullable value type. A nullable value type behaves in a similar manner to the original value type, but we can assign the null value to it. We use the question mark (?) to indicate that a value type is nullable, like this: int? i = null; //this is legal

Difference between IEnumerable and IEnumerator - By Shivprasad Koirala

Two very important concepts IEnumerable and IEnumerator, these concepts been always a confusing for many developers. Here comes a videos by Mr. Shivprasad Koirala (Trainer at Questpond ), watch this if you want to clear your confusions.

Executing multiple catch blocks in C#

Today I saw a discussion on FB questioning "Can multiple catch blocks be executed?". Many guys were confused in answering that question, few of them answered "YES". I am writing this post to support my answer. Here is a program in support with this answer. using System; using System.Linq;   namespace ConsoleApplication1 {       //Run this program and type 0 (that is numeric) and 'a' (that is char) on the console to check both catch blocks in action.     class Program     {         static void Main( string [] args)         {             try             {                 int numerator = 10;                 int denominator = GetText();                 int result = numerator / denominator;

Convert To Proper Case in C#

Introduction Here is a method which will convert your string in Proper Case, you just need to pass the string to this method and method will return the Proper Case string as a result. public string ConvertToProperCase(string str)         {             string formattedStr = null;             if (str == null)             {                 formattedStr = new System.Globalization.CultureInfo("en").TextInfo.ToTitleCase(str.ToLower());             }             return formattedStr;         }

Strings in C# - Part 3

Introduction MSDN Reference Just like C, C++ and Java, C# also provides some set of escape characters as shown below. (i) \'    : Inserts a single quote into a string literal. (ii) \"   : Inserts a double quote into a string literal. (iii) \\  : Inserts a backslash into a string literal. This can be quite helpful when defining file paths. (iv) \a : Triggers a system alert (beep). For console applications, this can be an audio clue to the user. (v) \b  : Triggers a backspace. (vi) \f  : Triggers from feed. (vii) \n : Inserts a new line on Win32 platforms. (viii) \r : Inserts a carriage return. (ix) \t  : Inserts a horizontal tab into the string literal. (x) \u  : Inserts a Unicode character into the string literal. (xi) \v : Inserts a vertical tab into the string literal. (xii) \0 : Represents NULL character. In addition to escape characters, C# provides the @ quote string literal notation called as 'verbatim string'. Using t

Extension Methods in C#

Introduction Extension methods are a convenient way to add methods to classes that you don’t own and so can’t modify directly. Look at the program given below: using System; using System.Collections.Generic;   namespace ConsoleApplication1 {     class Program     {         static void Main( string [] args)         {             //create the object of the class             Person p = new Person () { Name = "Abhimanyu" , Age = 22 };               //see the result             Console .WriteLine(p.Name + ", " + p.Age);             Console .ReadKey()

Using Object and Collection Initialize

Another tiresome programming task is constructing a new object and then assigning values to the properties, look at the example where I will be constructing object and then initializing its properties. using System; using System.Text;   namespace ConsoleApplication1 {     class Program     {         static void Main( string [] args)         {             //creating new StudentInfo object             StudentInfo studentInfo = new StudentInfo ();               //set the property values             studentInfo.ID = 1;             studentInfo.Name = "Abhimanyu" ;

Auto-Implemented Properties for trivial Get (getter) and Set (setter) in C#

In the example given below, you will look at a very good example on auto-implemented properties for trivial get (getter) and set (setter). There is a shortcut way to create property with its definition just by pressing keyboard keys. Find here Tips: shortcut way to create properties in C# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Automatically_Implemented_Properties {     class Program     {         static void Main( string [] args)         {             // Intialize a new object.             Customer cust1 = new Customer (500.50, "Abhimanyu" , 12);             //Modify a property       

Tips: Commenting and Uncommenting codes

In this video tutorial you are going to learn how to comment and uncomment your codes in a quick way.

Tips: shortcut way to create properties in c-sharp

You could type "prop" and then press tab, that will generate the following.         public TYPE Type { get; set; } Then you change "TYPE" and "Type"         public string myString {get; set;} You can also get the full property typing "propfull" and then tab, that would generate the field and the full property.         private int myVar;         public int MyProperty         {             get { return myVar;}             set { myVar = value;}         }

Arrays in C#

Introduction A normal variable can store any single data of same type whereas an array is a single data variable that can store multiple pieces of data each of the same type. Each of these elements is stored sequentially using index values in the computer's memory. In C#, index value starts with 0. The basic format of an array is given below: datatype[] variablename; 'datatype' indicates the type of information array will store namely int, char etc. The square bracket indicates that we are declaring array type variable and 'variablename' is the name of the array variable. decimal [] money; Above declaration creates variable that will hold decimal values, however we didn't set the piece of information to be stored. Let's do this by this code: decimal [] money; money = new decimal [8]; Above code is using declaration and initialization in two different lines, we can do this at the same time, as given below: decimal [] money = new decimal

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples