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

Friday, June 25, 2021

Hash Table in C#

 The Hashtable is a non-generic collection and used to store the key/value pairs based on the hash code of the key. Key will be used to access the element in the collection.

Hashtable Characteristics

  • Comes under System.Collection namespace
  • Keys must be unique and cannot be null.
  • Values can be null or duplicate.
  • Values can be accessed by passing associated key in the indexer e.g. myHashtable[key]
  • Elements are stored as DictionaryEntry objects.
  • “ContainsKey” can be used to check the key in the hash table.
URL: https://dotnetfiddle.net/Tb8E69

Monday, September 3, 2018

Repeat character without loop in C#

 you can use string constructor that accepts a char and the number of times to repeat it.

Example:

public class Program
{
public static void Main()
{
string tabs = new String('X',  4);
Console.WriteLine(tabs);
}
}

OUTPUT:
XXXX

Sunday, March 25, 2018

Right and Left padding in C#

Padding adds the space or any character to the right or left side.

PadRight: This method add the characters in right side and left align
PadLeft: This method add the characters in left side and right align



Saturday, March 24, 2018

Readonly and Constant in C#

Constant: Constant fields are define at the time of declaration and once they are defined can't be changed.
NOTE:
  1. This can't be declared static.
  2. Local scope 
  3. This is implicitly static variable.
  4. This must to initialised
Readonly: Readonly can be initialised either at the time of declaration or within the constructor of the same class and change the value in the same class constructor.


Thursday, March 22, 2018

Dictionary in C#

  • Dictionary is generic collection and includes System.Collections.Generic namespace.
  • This is collection of Key and value pair and key must be a unique.
  • In the dictionary, you cannot be including duplicate key. 
  • In the dictionary, duplicate key given run time error.

NOTE:

  1. It returns error if we try to find a key which does not exist.
  2.  It is faster than a hash table because there is no boxing and unboxing.
  3. Dictionary is a generic type which means we can use it with any data type.

List<T> in C#

List
  • Lists are strongly typed generic collections.
  • They will store values of different or same datatype.
  • List size will increase or decrease dynamically.
  •  Its defined in the System.Collections.Generic namespace
      Add item in List :

Thursday, March 1, 2012

Generic function call


 public class clsGeneric
    {
        public void show<T>(T value)
        {
            Type t = typeof(T);
            Console.WriteLine(t.Name + ":" + value);
        }
    }


 class Program
    {
         static void Main(string[] args)
        {
             clsGeneric ng;
            ng = new  clsGeneric();
            int a = 10;
            ng.show(a);
            string b = "SS";
            ng.show(b);

            Console.WriteLine("Press any key to close........");
            Console.ReadKey();
        }
    }

OUTPUT
----------------------------
Int32:10
String:SS
Press any key to close........



use global variable with same name of Local variable


 public class Demo1
    {
        int a = 10;
        public  void ff()
        {
            int a = 11;
            Console.WriteLine("a={0}", this.a);
        }


   class Program
    {
        static void Main(string[] args)
        {
              Demo1 ng = new   Demo1();
             ng.ff();

            Console.WriteLine("Press any key to close........");
            Console.ReadKey();

        }
}


Output:
-----------------------------------
a=10
Press any key to close........
-----------------------------------

Tuesday, February 7, 2012

Regular Expression


Regular Express class and validation done himself.

SqlCommand Query based on parameters


SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Emplyoee emp WHERE  emp.Name=@EmpName";
command.Parameters.Add(new SqlParameter(" @EmpName", 50));

// Execute the SQL Server command...
SqlDataReader reader = command.ExecuteReader();
DataTable tblemplyee = new DataTable();
tblemplyee.Load(reader);

foreach (DataRow rowProduct in  tblemplyee.Rows)
{
    // Use the data...
}


NOTE: This is a good way to block SQL injection

"" vs String.Empty

String.Empty is faster than "" because it doesn't create a new string object instance. Creating new instances brings penalties on both execution speed and memory usage.

Example:
// Slowest
str1 == "";
// Slow
str1.Equals(" ") == false
//Fast
str1 == String.Empty
// Fastest
str1.Equals(String.Empty) == false

Monday, January 23, 2012

Working with Nullable Types

******************* Type 1 ***********************
int iUnits;
int iStock ;
if (iStock== null)
  {
      iUnits= 0;
   }
else
 {
     iUnits= (int)iStock;
}

******************* Type 2 ***********************
// using the coalesce operator, ??,
    int iUnits= iStock ?? 0; 
The coalesce operator works like this: if the first value (left hand side) is null, then C# evaluates the second expression (right hand side).

Declare Null datetime variable

****************** Type 1 *********************
System.Nullable<DateTime> dt;
dt = null;

****************** Type 2 *********************
DateTime? dt1;
dt1 = null;

How to Use foreach in Multiple classes

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

namespace Indexer
{

public class NameDetail
{
public string FirstName { get; set; }
public string MiddleName{ get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
String strFullname="";
if (string.IsNullOrEmpty(FirstName) == false )
{
strFullname = FirstName;
}
if (string.IsNullOrEmpty(MiddleName) == false)
{
strFullname += MiddleName;
}
if (string.IsNullOrEmpty(LastName) == false)
{
strFullname += LastName;
}
return strFullname.Trim();
}

}
}

public class Name: IDisposable, IEnumerable, IEnumerator
{
List arrPos = new List();
public int count { get ;set ;}
private int Position = -1; // This is for Ienum interface

public NameDetail this[int pos]
{
get
{
try
{
return arrPos[pos];
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
set
{
if (arrPos.Count <= pos)
{
arrPos.Insert(pos, value);
count = arrPos.Count;
}
else
{
throw new Exception("No Index postiion");
}
}
}
#region IDisposable
public void Dispose()
{
arrPos = null;
}
#endregion IDisposable


//**********************************************************
//********************* Use For Each in object *************
//*********************************************************
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
public bool MoveNext()
{
if (Position < arrPos.Count - 1)
{
++Position;
return true;
}
return false;
}
public void Reset()
{
Position =-1;
}
public object Current
{
get
{
return arrPos[Position];
}
}
#endregion
}



class Program
{
static void Main(string[] args)
{
Name a = new Name();
NameDetail ND ;
ND = new NameDetail();
ND.FirstName = "Mohit";
ND.LastName = "Agrawal";
a[0] = ND;
ND = new NameDetail();
ND.FirstName = "aaa";
a[1] = ND;

foreach (NameDetail n in a)
{
Console.WriteLine(n.FirstName );
Console.WriteLine(n.MiddleName);
Console.WriteLine(n.LastName );
Console.WriteLine(n.FullName);
}
Console.ReadKey();
a.Dispose();
a = null;
ND = null;
}
}
}

Hash Table in C#

 The Hashtable is a non-generic collection and used to store the key/value pairs based on the hash code of the key. Key will be used to acce...