Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, May 1, 2024

Exploring the Distinctions Between IEnumerable and IQueryable Interfaces in C#

 In C#, IEnumerable and IQueryable are both interfaces that represent collections of data, but they have different characteristics and are used in different scenarios.


IEnumerable:
  • IEnumerable<T> is the simplest form of collection interface in C#. It represents a forward-only cursor of elements.
  • It is the most basic type for iterating over a collection of objects.
  • It resides in the System.Collections namespace.
  • It supports LINQ operations, but they are performed locally (in-memory). That means if you perform LINQ operations on an IEnumerable, all the data will be loaded into memory first, and then the query will be executed on that in-memory data.
  • Generally used for querying data from in-memory collections like arrays, lists, or other IEnumerable implementations.

// IEnumerable example

IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

var result = numbers.Where(x => x > 2).ToList(); // LINQ query executed in memory 


IQueryable:

  • IQueryable<T> inherits from IEnumerable<T> but extends its capabilities by adding support for querying data from various data sources like databases (via LINQ to SQL, Entity Framework, etc.).
  • It resides in the System.Linq namespace.
  • It represents a query that can be executed on a specific data source.
  • It allows for deferred execution, meaning the query is not executed until the result is actually enumerated.
  • Queries written against IQueryable are translated into the native query language of the underlying data source (e.g., SQL for a relational database) and executed on the server-side, which can lead to better performance by only fetching the necessary data.
  • Used for querying data from external data sources where the data may not reside entirely in memory.


 Example:-

// Create a list of customer objects

List<Customer> customersList = new List<Customer>

{

    new Customer { Id = 1, Name = "Alice", Age = 25 },

    new Customer { Id = 2, Name = "Bob", Age = 30 },

    new Customer { Id = 3, Name = "Charlie", Age = 18 },

};

// Create an IQueryable collection from the list

IQueryable<Customer> customersQuery = customersList.AsQueryable();

// Perform a LINQ query on the IQueryable collection

var result = customersQuery.Where(c => c.Age > 18).ToList();

 
"IEnumerable" is used for querying in-memory collections, while "IQueryable" is used for querying external data sources with deferred execution and query translation capabilities.

 

 

Sunday, May 9, 2021

Private Constructor In c#

 In this article i will explain what is private constructor and what is the use of  private constructor.

When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. 

Some key points of a private constructor are:

  • It provide an implementation of a singleton class pattern. 
  • One use of private  constructor is when we have only static members of class.
  • If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.   
 
using System;
                    
public class Program
{
    public static void Main()
    { 
 
 // If you uncomment the following statement, it will generate
        // an error because the constructor is inaccessible:
        // Counter aCounter = new Counter();   // Error
 
        Counter.currentCount=100;
        Console.WriteLine("Counter before increment {0}",Counter.currentCount);
        Counter.IncrementCount();
        Console.WriteLine("Counter after increment {0}",Counter.currentCount);
    }
}
public class Counter
{
    private Counter() { }

    public static int currentCount;

    public static int IncrementCount()
    {
        return ++currentCount;
    }
}
 
Output : 
Counter before increment 100
Counter after increment 101 
 

When we use private constructor:

  • Use private constructor when class have only static members.
  • Prevents the creation of instance of that class.
  • If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor

Static constructor in c#

In this article i will explain what static constructor in c# and what is use of the static constructor in c#.

 The static constructor creating by use of the static keyword in c# class. static constructor invoked only once for all of the instances of the class and it is invoked during the creation of first instance of the class or the first reference to the static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.  

Key points of the static constructor  : 

  • Static constructor does not have access modifier or have parameter.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • Static constructor can not we called directly.
  • The use has no control over when static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file

 The following example is the use static constructor:


using System;
                    
public class Program
{
    public static void Main()
    {
        Circle c1=new Circle(5);
        Console.WriteLine("Area of circle is {0}",c1.CalculateArea());
    }
}
public class Circle
    {
        static float _PI;
        int _Radius;
        static Circle()
        {
            Circle._PI = 3.14f;
        }
        public Circle(int radius)
        {
            this._Radius = radius;
        }
        public float CalculateArea()
        {
            return Circle._PI * this._Radius * this._Radius;
        }
    }
 
Output : 
 
Area of circle is 78.5 

Copy Constructor

 The constructor which creates an object by coping variable from another object is called copy constructor. the purpose of copy constructor is to initialize a new instance to values of existing instance.

The copy constructor is invoked by instantiating an object of type employee and bypassing it the object to be copied

 using System;

                    
public class Program
{
    public static void Main()
    {
        Employee emp=new Employee(101,"Aman");
        
        Employee copyEmp=new Employee(emp);
        Console.WriteLine("Id of Employee {0}",copyEmp.Id);
        Console.WriteLine("Name of Employee {0}",copyEmp.name);
    }
}
public class Employee{
    public int Id;
    public string name;
    public Employee(int id,string empName){ //Instance constructor
        this.Id=id;
        this.name=empName;
    }
    public Employee(Employee emp){ //Declaring copy constructor
        this.Id=emp.Id;
        this.name=emp.name;
    }
    
}
 
Output : 
 
Id of Employee 101
Name of Employee Aman 
 

Parameterized Constructor

In the class constructor contain at least one parameter is called parameterized constructor. The advantage of the parameterized constructor is that we can initialize each instance with different values at the time of object creation of the class.

Following is the example of the parameterized constructor:


using System;
                    
public class Program
{
    public static void Main()
    {
        Employee emp=new Employee(101,"Aman");
        Console.WriteLine("Id of Employee {0}",emp.Id);
        Console.WriteLine("Name of Employee {0}",emp.name);
    }
}
public class Employee{
    public int Id;
    public string name;
    public Employee(int id,string empName){
        this.Id=id;
        this.name=empName;
    }
}
 
Output : 
Id of Employee 101
Name of Employee Aman
 
 

Default Constructor

In this article i will explain what is default constructor of class in c#.

The constructor of the class which do dot have any parameter is called default constructor. In other word this type of constructor does not takes parameters. The disadvantage of default constructor is that every instance of the class will be initialized as the same  values of class variables. So we can not initialized each instance of the class with different values.

The default constructor initializes :

  • All numeric variables to zero.
  • All string variables to null.

 

using System;
                    
public class Program
{
    public static void Main()
    {
        Lab1 l=new Lab1();
        Console.WriteLine("Value of a {0}",l.a);
        Console.WriteLine("Value of name {0}",l.name);
    }
}
public class Lab1{
    public int a;
    public string name;
    public Lab1(){
        a=10;
        name="Brij";
    }
}
 
Output : 
Value of a 10
Value of name Brij 

Saturday, May 8, 2021

Constructor In C#?

 In this article I will explain what is constructor in class, use of constructor and types of constructor.

The constructor basically special method of class that is automatically invoked when instance of class is created is called the constructor. The use of the constructor are initialize the private filed of the class while creating the instance of the class. when you have not created the constructor of the class, the compiler automatically create the default constructor. The default constructor initialize the all numeric filed to zero and all string filed to null.

using System;
                   
public class Program
{
    public static void Main()
    {
        Lab1 l=new Lab1();
        Console.WriteLine("Value of a {0}",l.a);
        Console.WriteLine("Value of name {0}",l.name);
    }
}
public class Lab1{
    public int a;
    public string name;
}

Output : 

Value of a 0
Value of name null

In the above example when we have create the instance of the class then automatically constructor are created and initialize the value of a is 0 and name is null.


Some important information about the constructor : 

  • A class can have any number of constructors.
  • A constructor does not have any return type like int, float and string even void.
  • A static constructor can not be parameterized constructor.
  • within a class, you can create only on static constructor.

 

Types of constructor :  

  1. Default Constructor 
  2. Parameterized Constructor  
  3. Copy Constructor  
  4. Static constructor 
  5. Private Constructor 

Monday, April 5, 2021

Write the C# program to print the following pattern?

 

using System;

 

public class Program

{

  public static void Main()

  {

  for(var i=0;i<5;i++){

           for(var k=1;k<(5-i);k++){

                 Console.Write(" ");

           }

          for(var k=0;k<(2*i+1);k++){

                 Console.Write("*");

           }

      Console.WriteLine("");

     }

  }

}

}

Write the C# program to print the following pattern?

 

using System;

 

public class Program

{

  public static void Main()

  {

  for(var i=0;i<5;i++){

           for(var k=1;k<(5-i);k++){

                 Console.Write(" ");

           }

          for(var k=0;k<(i+1);k++){

                Console.Write("*");

           }

       Console.WriteLine("");

     }

   }

}

Tuesday, February 23, 2021

Immutability of String Objects In C#

String objects are immutable, they  cannot be changes after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new object.

For example: 

When the contents of s1 and s2 are concatenated to form a single string, the two original string are unmodified. The += operator creates a new string that contains the combined contents. That  new  object is assigned to the variable s2, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "Hello ";
string s2 = "World";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.

s1 += s2;
System.Console.WriteLine(s1);

// Output: A string is more than the sum of its chars.



System.String vs string in c#

In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating and comparing strings.

Declaring and Initializing Strings
// Declare without initializing.
string message1;
// Initialize to null.
string message2 = null;
// Initialize as an empty string.
// Use the Empty constant instead of the literal "".
string message3 = System.String.Empty;
// Initialize with a regular string literal.
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";
// Initialize with a verbatim string literal.
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";
// Use System.String if you prefer.
System.String greeting = "Hello World!";
// In local variables (i.e. within a method body)
// you can use implicit typing.
var temp = "I'm still a strongly-typed System.String!";
// Use a const string to prevent 'message4' from
// being used to store another string value.
const string message4 = "You can't get rid of me!";
// Use the String constructor only when creating
// a string from a char*, char[], or sbyte*. See
// System.String documentation for details.
char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);





Saturday, February 13, 2021

String In C#

A String is a sequential collection of characters that's used to represent text. A String object is a sequential collection of System.Char objects that represent a string. The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only). 

The maximum of a String object in memory 2-GB ,or about 1 billion characters.

Instantiate to String Object:

Assigning a string literal to a String variable. This is the most commonly used method for creating a string. The following example uses assignment to create several strings. Note that in C#, because the backslash (\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted.

class Program

    {
        static void Main(string[] args)
        {
            string myStr = "this is string creation by assignment!";
            Console.WriteLine(myStr);
            string myafilePath = "Location of file c:\\docs\\test-file.doc";
            Console.WriteLine(myafilePath);

            string myafilePath2 = @"Location of file c:\docs\test-file.doc";
            Console.WriteLine(myafilePath2);

            Console.ReadKey();
        }
    }



Sunday, November 15, 2020

Variables in C#

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords), for example:

int - stores integers (whole numbers), without decimals, such as 123 or -123

double - stores floating point numbers, with decimals, such as 19.99 or -19.99

char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

string - stores text, such as "Hello World". String values are surrounded by double quotes

bool - stores values with two states: true or false

Declaration of variable:

To declaring a variables, you must be specify the type of variable and assign it value.

Syntax:

type variable_Name = some value;

Where type is a C# type (such as int or string), and variable_Name is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

Example: - 1

Create the type string variable as name and assign the value john and print on console.

string name="john"

Console.WriteLine(name);

Example: - 2

Create the type int variable as myValue and assign the some numeric value.

int myValue=25;

Console.WriteLine(myValue);


Constants Variables in C#:

However, you can add the const keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "constant", which means unchangeable and read-only):

const int myValue=15;

Console.WriteLine(myValue);

myValue=25;// here give the Error

We can not assign new to constant variable.

The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won't mess up your code. An example that is often referred to as a constant, is PI (3.14159...).

Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.

C# Identifiers:

All C# variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

Example:

int seconds=60;

//Good to understand

int s=60;

// OK, but not so easy to understand what m actually is


Note:
  1. Names can contain letters, digits and the underscore character (_)
  2. Names must begin with a letter
  3. Names should start with a lowercase letter and it cannot contain whitespace
  4. Names are case sensitive ("myVar" and "myvar" are different variables)
  5. Reserved words (like C# keywords, such as int or double) cannot be used as names

For more information about variables, Please visit Here

Write the C# program for the following pattern

 

 class Program
    {
        static void Main(string[] args)
        {
            int n = 5;
            int space;
            for (int i = 1; i <= n; i++)
            {
                for (space = 1; space <= (n - i); space++)
                {
                    Console.Write(" ");
                }
                for (int j = 1; j <= i; j++)
                {
                    Console.Write(j);
                }
                for (var k = (i - 1); k >= 1; k--)
                {
                    Console.Write(k);
                }
                Console.WriteLine();
            }
        }
    }



Monday, October 26, 2020

Build-in Types in c#

Boolean Type : Only true or false
Integral Types : sbyte,byte,short,ushort,int,uint,long,ulonf,char
Floating Types : float and Double
Decimal Types
String Types


Escape Sequences Types:

\a    Bell (alert)
\b    Backspace
\f    Form feed
\n    New line
\r    Carriage return
\t    Horizontal tab
\v    Vertical tab
\'    Single quotation mark
\"    Double quotation mark
\\    Backslash
\?    Literal question mark
\ ooo    ASCII character in octal notation
\x hh    ASCII character in hexadecimal notation
\x hhhh    Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal.

Verbatim Literal


Is a string with an @ symbol prefix, as in @"hello"

Verbatim Literals make escape sequence translate as normal printable characters to enhance readability.

   class Program
    {
        static void Main(string[] args)
        {
            //String type
            string Name="Brijpal";
            Console.WriteLine("Name {0}", Name);
            string NameWithDoubleQuate = "\"Brijpal\"";
            //using escape character for new line
            Console.WriteLine(NameWithDoubleQuate);
           
            string path = "E:\\C# Video";
            Console.WriteLine(path);
            //Usig Verbatim Literals
            string pathwithLiteral = @"E:\C# Video";
            Console.WriteLine(pathwithLiteral);
            string str = "One\nTwo\nThree";
            Console.WriteLine(str);
            Console.ReadLine();
        }
    }  


Sunday, October 25, 2020

Static and Instance member in C#

The members of a class that can not be accessed without creating an instance for the class are called as instance members.

The members of a class that can be accessed without creating an instance and directly by using class name are called as static members.

The following example using instance member:

    class Circle

    {

        float _PI = 3.14f;

        int _Radius;

        public Circle(int radius)

        {

            this._Radius = radius;

        }

        public float CalculateArea()

        {

            return this._PI * this._Radius * this._Radius;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Circle C1 = new Circle(5);

            float area1 = C1.CalculateArea();

            Console.WriteLine("Area {0}",area1);

            Circle C2 = new Circle(6);

            float area2 = C2.CalculateArea();

            Console.WriteLine("Area {0}", area2);

            Console.ReadLine();

        }

    }

When using instance member  _PI occupied memory every time when circle object are created.



The following example using static member:

    class Circle

    {

        static float _PI;

        int _Radius;

        static Circle()

        {

            Circle._PI = 3.14f;

        }

        public Circle(int radius)

        {

            this._Radius = radius;

        }

        public float CalculateArea()

        {

            return Circle._PI * this._Radius * this._Radius;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Circle C1 = new Circle(5);

            float area1 = C1.CalculateArea();

            Console.WriteLine("Area {0}",area1);

            Circle C2 = new Circle(6);

            float area2 = C2.CalculateArea();

            Console.WriteLine("Area {0}", area2);

            Console.ReadLine();

        }

    }



  • When a class member includes a static modifier, the member is called as static member.
  • When no static modifier present the member is called as non static member or instance member.
  • Static members are invoked using class name, where as instance member are invoked instances (objects) of class.
  • An instance member belongs to  specific instance(object) of a class. If I create 3 objects of class, I will have 3 sets of instance member in memory, where as there will ever be only one copy of a static member, no matter how many instances of a class created. 
NOTE: Class members => Fields, methods, properties, events, indexers, constructors.

Reading and writing to console in C#

In the C# programming language Console.ReadLine() method are used to read the input string from console. Console.WriteLine() method are used to write the content to console.

There are two way to write any text to console using Console.WriteLine() method.

  • Concatenation 
  • Place holder syntax - Most preferred
Example:

    class Program
    {
        static void Main(string[] args)
        {
            //Writes the specified string, followed by the current line terminator, to the standard output stream 
            Console.WriteLine("Please enter first name : ");

            //Reads the next line of characters from the standard input stream
            string first_Name = Console.ReadLine();

            Console.WriteLine("Please enter last name : ");
            string last_Name = Console.ReadLine();

            //print full name using place holder
            Console.WriteLine("Full Name {0} {1}",first_Name ,last_Name);

            // here print full using concatenation string
            Console.WriteLine("Full Name "+first_Name+last_Name);

            Console.ReadLine();
        }
    }

Output:

Introduction to C#

C# is pronounced "C-Sharp". It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.

C# is a . NET language, meaning that it targets web development as one of its main purposes. 

It is a beginner-friendly language, but you also need to learn about ASP.NET.

C# works with ASP.NET to create web applications.

Hello world program in C#:

//Namespace Declaration

using System;

class Program

{

        public static void Main() { //Main is the entry point of application

        //Write to console

        Console.WriteLine("Hello world");

    }

}

Using System Declaration:

  • The Namespace declaration, using system, indicates that you are using the System namespace.
  • A Namespace is used to organize your code and is collection of classes, structs, interfaces, enums and delegates.
  • Main method is the entry point into your application.

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...