Optional Parameter in C#

Optional parameter is one of the good feature of C# language, this feature allow developer to write the code with default of parameters in case user not supplying input.

Lets take an example to understand how it works. Here in the example I have created a class called MyClass and constructor with two parameters FirstName and LastName.
Where LastName is optional.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class MyClass
    {
        public string FirstName { get; private set; }
        public string LastName { get; private set; }

        public MyClass(string firstName, string lastName = "") {
            FirstName = firstName;
            LastName = lastName;
        }

        public string SayHello(string name) {
            return "Hello there, " + name;
        }

        public string SayHello(MyClass objMyClass){
            return SayHello(objMyClass.FirstName + " " + objMyClass.LastName);
        }
    }
}

Note*: For first name and last name, I have added the private keyword against the set accessor because I don’t want to allow it to be set from outside the class.
This also another way to make a property readonly from out side the class but read / write from same class.

Lets test the above optional parameter example using below code.

MyClass objWhiteX = new MyClass("White", "X");
MyClass objWhite = new MyClass("White");

Console.WriteLine(objWhite.SayHello(objWhiteX));
Console.WriteLine(objWhite.SayHello(objWhite));

You will get the below result.
Optional

#optional-parameter-in-c

Assign null to ValueType datatype

As we know, memory allocation and data store in memory done in two different ways when we create the object of datatype.

One is data store and assigned to object variable in memory when we create it using value type data type (By Value).

Second way is when we create the object of a class variable then that abject points to the memory location (By Reference).

Object created using by reference option can have null value (like Class Object). The object created using by Value cannot have null value.

Let’s take an example to create an object of integer data type and assign null value to it

int intVariable = null;

When we compile this code compiler generates the below error message.

Error: Cannot convert null to ‘int’ because it is a non-nullable value type

But, there is situation where we need to pass the null values while inserting data for this data type. This can  be achieve using the below code.

int? intVariableWithNull = null;

The above code (‘?’ with datatype) will allow us to create an object of int data type and assign null value to it.

 

#valuetype-with-null-value

Difference between string and String in C#

Most of the time we get confused about the string and String class in C#.

Technically, there is no difference between string and String.

string is the Alias for the System.String class. It is just a coding guideline. Microsoft recommended coding style says that, use the string whenever we are creating object of string data type and use String class whenever we want to access the functions of the string class.

Example:

string foo = "world";
string bar = String.Format("Hello {0}!", foo);


 

#string-and-string

Serialize and Deserialize object using C#

Below shown is the very simple and easiest code example to serialize and deserialize the class object using XmlSerializer.

System imports are:

using System.Xml;
using System.IO;
using System.Xml.Serialization;

 

Actual Code:

clsPerson p = new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
// Assuming p is an instance of an object
XmlSerializer ser = new XmlSerializer(p.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, p);

XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
System.Type objType = p.GetType();
XmlSerializer ser1 = new XmlSerializer(objType);
object obj = ser1.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
clsPerson p1 = (clsPerson)obj;

 

Class:

public class clsPerson {
        public string FirstName;
        public string MI;
        public string LastName;
}

DML on View

Many times question came in our mind and we got confused about whether we can perform the data manipulation operations on views or not. The answer to this question is, it depends on how we have created the views. Let’s take a simple example to understand it.

CREATE TABLE Employees(EmployeeId int Not Null Identity (1,1), EmployeeName varchar(100))
GO
INSERT INTO Employees(EmployeeName) VALUES ('Abc')
GO
INSERT INTO Employees(EmployeeName) VALUES ('Xyz')
GO
SELECT * FROM Employees
GO

View1

Now create the view on employee table as shown below and try to insert the value using it.

CREATE VIEW vw_Employees AS SELECT * FROM Employees WITH CHECK OPTION
GO
INSERT INTO vw_Employees (EmployeeName) VALUES ('Pqr')
GO
SELECT * FROM vw_Employees 
GO

View2

As shown in above fig. data successfully inserted into the employee table using view. To understand how “WITH CHECK OPTION” work along with view. Let’s take another example. Create another table employee2 and create view on it with where clause to filter the data for employee id 2 using below SQLs

CREATE TABLE Employees2(EmployeeId int, EmployeeName varchar(100))
GO
INSERT INTO Employees2(EmployeeId, EmployeeName) VALUES (1,'Abc')
GO
CREATE VIEW vw_Employees2 AS SELECT * FROM Employees2 WHERE EmployeeId = 2 WITH CHECK OPTION
GO
SELECT * FROM Employees2 
GO

View3

As you can see, there is one record in employee2 table which we have inserted using insert statement on table. We have created view vw_employee2 on employee2 table with filter on employeeid 2. Now try to insert the record for employee id 2 first and check the result.

INSERT INTO vw_Employees2 (EmployeeId, EmployeeName) VALUES (2,'asd')
GO
SELECT * FROM vw_Employees2

View4

As you can see, data inserted successfully in table. Now try to insert the record in employee2 table using view for employeeid 1.

INSERT INTO vw_Employees2 (EmployeeId, EmployeeName) VALUES (1,'Asdf')
GO

It throws the below SQL exception

Msg 550, Level 16, State 1, Line 25
The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.
The statement has been terminated.

Summary: Yes we can perform the DML operation on View but it depends on how we have created it.

#dml-on-view

Export data set into Excel using Closed XML

Below is the simple code example to export the DataSet into an Excel using ClosedXML dll.

private static void ExportDataSet(DataSet ds, string destination)
{
          var workbook = new ClosedXML.Excel.XLWorkbook();
          foreach (DataTable dt in ds.Tables) {
                  var worksheet = workbook.Worksheets.Add(dt.TableName);
                  worksheet.Cell(1, 1).InsertTable(dt);
                  worksheet.Columns().AdjustToContents(); 
          }
          workbook.SaveAs(destination);
          workbook.Dispose();
}

#closedxml-to-export-data-set

Linq on data table

Below is the code to read the data from data table using linq.

You cannot directly use the data table as you use collection object and specify the linq expression. For data table you need to convert its content which represent collection using AsEnumerable() method.

Example:

var Data = (from p in yourDataTable.AsEnumerable() Select p

 

#linq-on-data-table