virtual modifier in C#

virtual method can be redefined. The virtual keyword designates a method that is overridden in derived classes. We can add derived types without modifying the rest of the program. The runtime type of objects thus determines behavior.

Keywords

Example

C# language

This program introduces two classes, A and B. Class A has a public virtual method called Test. Class B, meanwhile, derives from class A and it provides a public override method called Test as well.
Tip:The virtual modifier tells the compiler that when any class derived from class A is used, an override method should be called.

Override

Program that introduces virtual method: C#

using System;

class A
{
public virtual void Test()
{
Console.WriteLine("A.Test");
}
}

class B : A
{
public override void Test()
{
Console.WriteLine("B.Test");
}
}

class Program
{
static void Main()
{
// Compile-time type is A.
// Runtime type is A as well.

A ref1 = new A();
ref1.Test();

// Compile-time type is A.
// Runtime type is B.

A ref2 = new B();
ref2.Test();
}
}

Output

A.Test
B.Test
With virtual methods, the runtime type is always used to determine the best method implementation.
In Main,
ref1 has a compile-time
and runtime type of A. On the other hand, ref2 has a compile-time type of A but a runtime type of B.

Discussion

Question and answer

Why would you need to use virtual methods? Your program may be designed in such a way that you do not know all the types of objects that will occur when it is executed. You can provide a standard (base) type and design around that type.
Then, you can re-implement important functionality depending on the more specific (derived) types. When you call a method on the base type, you invoke the more derived (and useful) method.

Abstract

Abstract:The term abstract refers to a conceptual type, one that specifies common characteristics but lacks an implementation.
Tip:An abstract class then is used as a template for derived classes that can actually exist.

Abstract

Private virtual

Private keyword

Private virtual methods cannot be declared in the C# language. In programming languages, polymorphism based on types is a way to virtualize the entry point to a data object. For private methods, you have already entered the data object.
Thus:No virtualized entry point is ever required.
And a private virtual method is not useful.

In this example, we see both a program that attempts to use a private virtual method member, as well as the compile-time error that the program triggers. As a reminder, the error occurs during the static compilation phase.
And:This means that no program that declares a private virtual method will ever be executed in any way.
Program that uses private virtual method: C#

class A
{
private virtual int Test()
{
return 1;
}
}

class Program
{
static void Main()
{
}
}

Compile-time error

Error 1
'A.Test()': virtual or abstract members cannot be private

Squares: abstract

Virtual methods are an implementation of type-based polymorphism. When you have a derived class and a base class, the derived class can re-implement the base class virtual method. This gives you a dynamic entry point to the class type.
Note:This enables you to clearly separate the usage of the type from the implementation of each subtype.
Whenever a private method is invoked,the type has already been entered. You can always define custom private methods on a type. If you are already inside the type, you can simply call a regular instance private method.
Further:Instance and static methods are faster to invoke than interface and virtual methods.

Static MethodNot equal

Notice:Unlike in the C# language, private virtual methods are allowed in the C++ programming language.
And:They are used in some design patterns that emphasize the importance of overriding only certain pieces of an algorithm.

Summary

Virtual specifies that the method can be overridden in derived types. It tells the compiler to generate code that selects an override method. A virtual method can have an implementation. It is called like any other method.

abstract modifier in C#

An abstract method has no implementation. Its implementation logic is provided instead by classes that derive from it. We use an abstract class to create a base template for derived classes.

Keywords

Example

We introduce first an abstract class named Test.
Two other classes derive from Test:
the Example1
and Example2 classes. In the Test class, we have a field, and an abstract method.

Piece of computer software: a program

Methods:Abstract methods cannot have bodies. This makes sense: these bodies would never be used.
Classes:Abstract classes have certain restrictions.
They cannot be constructed directly.
Tip:These are features.
They enforce a design concept.
An abstract type is, by definition, not a concrete one.
Program that uses abstract class: C#

using System;

abstract class Test
{
public int _a;
public abstract void A();
}

class Example1 : Test
{
public override void A()
{
Console.WriteLine("Example1.A");
base._a++;
}
}

class Example2 : Test
{
public override void A()
{
Console.WriteLine("Example2.A");
base._a--;
}
}

class Program
{
static void Main()
{
// Reference Example1 through Test type.
Test test1 = new Example1();
test1.A();

// Reference Example2 through Test type.
Test test2 = new Example2();
test2.A();
}
}

Output

Example1.A
Example2.A

Squares

Derived classes. When you create a derived class like Example1 or Example2, you must provide an override method for all abstract methods in the abstract class. The A() method in both derived classes satisfies this requirement.

Override

Int field. An abstract class can have an instance field in it. The derived classes can access this field through the base syntax. This is a key difference between abstract classes and interfaces.

Int

Cannot instantiate abstract class. The important part of an abstract class is that you can never use it separately from a derived class. Therefore in Main you cannot use the new Test() constructor.
However:You can use the Test type directly once you have assigned it to a derived type such as Example1 or Example2.

Discussion

Question

What is the difference between an abstract class and an interface? An abstract class can have fields on it. These fields can be referenced through the derived classes. An interface, on the other hand, cannot have fields.

Interface

Thus:An abstract class is essentially the same thing as an interface except it is an actual class, not just a contract.

Note

A static class cannot be abstract. Static classes cannot be instantiated or derived from. This makes the abstract keyword have no meaning for them. Abstract classes have effect only when used with inheritance.
Static:A static class is a class with additional restrictions placed upon it. With “static” on a class, we take away features.

Static Class

Performance

Performance optimization

In my testing, abstract classes with virtual methods have better performance than interface implementation in the .NET Framework 4.0. We show that performance remains the same with an abstract class instead of a regular class.

Interface Performance

In my view, programs that use abstract classes tend to be better-designed. Less code duplication occurs in them.
With less code,
we tend to have higher-quality
and better-tested code. This leads to faster and more reliable programs.
So:In solving the problem of code duplication among many object types, abstract classes help improve code quality and performance.

Summary

C# language

An abstract class is one that cannot be directly instantiated. Instead, derived classes must inherit from it—their constructors must be used. Compared to an interface, it adds features and improves performance.
Review:Abstract classes use the abstract keyword.
Abstract methods use a special form.
The method body is replaced by a semicolon.

Partial Classes in C#

Partial Class

In this article I will explain what is a partial class? What are the benefits of using partial classes and how to implement partial classes in your C# applications. 
Partial class is a new feature added to C# 2.0 and Visual Studio 2005. It is supported in .NET Framework 2.0. If you are working with .NET 1.0 or 1.1, partial classes may not work. 
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
Benefit of partial classes:
1) More than one developer can simultaneously write the code for the class.
2) You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.
There are a few things that you should be careful about when writing code for partial classes: 
  • All the partial definitions must proceeded with the key word “Partial”.
  • All the partial types meant to be the part of same type must be defined within a same assembly and module.
  • Method signatures (return type, name of the method, and parameters) must be unique for the aggregated typed (which was defined partially).
  • The partial types must have the same accessibility.
  • If any part is sealed, the entire class is sealed.
  • If any part is abstract, the entire class is abstract.
  • Inheritance at any partial type applies to the entire class.
I have attached code of the partial classes along with this article. You can open the project and understand the functionality.
Hope the article would have helped you in understanding what partial classes are. Waiting for your feedback.

Access Modifiers in C#

Access modifiers are keywords used to specify the declared accessibility of a member or a type.

Why to use access modifiers?

Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn’t have access to certain features.

In C# there are 5 different types of Access Modifiers.
Modifier
Description
public
There are no restrictions on accessing public members.
private
Access is limited to within the class definition. This is the default access modifier type if none is formally specified
protected
Access is limited to within the class definition and any class that inherits from the class
internal
Access is limited exclusively to classes defined within the current project assembly
protected internal
Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.

  • public 
    -No restrictions to access
    -The type or member can be accessed by any other code in the same assembly or another assembly that references it.
  • protected 
    -Access is limited to within the class definition and any class that inherits from the class.
    -The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
  • internal 
    -Access is limited exclusively to classes defined within the current project assembly.
    -The type or member can be accessed only by code in the same class or struct.
  • private 
    -Access is limited to within the class definition; This is the default access modifier type if none is formally specified.
    -The type or member can be accessed by any code in the same assembly, but not from another assembly.

What is an access modifier?

Access modifiers are keywords used to specify accessibility of a member or a type.
An access modifier allows us a way handle which member or type has an access or not has an access to certain features in a program.
For example if you want to hide or encapsulate particular member or type outside the class scope then you achieve this through access modifier only or if you want to expose particular member or type outside the class scope then you achieve this through access modifier only.

Types of access modifiers

Private
Protected
Public
Internal
Protected Internal

Private Access Modifier

The private keyword is a member access modifier.
Private members are accessible only within the body or scope of the class or the struct in which they are declared.
We can declare private access modifier to a class, method, property, structure, interfaces.
However if we do not specific any access modifier to a class, method, property, structure it will be assumed as private member only.
Example :
1 public class Employee
2 {
3     private void DisplayEmployeeDetails(){
4 Console.WriteLine("Employee Name --> Onlinebuff and Employee Code --> 009");
5     }
6 }
In above the code we have class “Employee” with “private” method “DisplayEmployeeDetails” which displays employee details.

Public Access Modifier:

The public keyword is a member access modifier.
Public members are accessible anywhere in program or application.
There is no restriction to access public access modifiers.
We can declare public access modifier to a class, method, property, structure, interfaces.
Example :
1 public class Employee
2 {
3     Public void DisplayEmployeeDetails(){
4 Console.WriteLine("Employee Name --> Onlinebuff and Employee Code --> 009");
5     }
6 }
In above the code we have class “Employee” with “public” method “DisplayEmployeeDetails” which displays employee details.

Protected Access Modifier:

The protected keyword is a member access modifier.
Protected members are accessible within the body or scope of the class or the struct in which they are declared and if protected member is declared in base class (Parent class) then it is also accessible in derived class (child class)  only if access takes place through derived class type.
We can declare protected access modifier to a class, method, property, structure, interfaces.
Example :
1 public class Employee
2 {
3     Protected void DisplayEmployeeDetails(){
4 Console.WriteLine("Employee Name --> Onlinebuff and Employee Code --> 009");
5     }
6 }
In above the code we have class “Employee” with “protected” method “DisplayEmployeeDetails” which displays employee details.

Internal Access Modifier:

The internal keyword is a member access modifier.
Internal members are accessible within the same namespace scope in which it is declared or it is accessible in same assembly or same project.
We can declare internal access modifier to a class, method, property, structure, interfaces.
Example :
1 public class Employee
2 {
3     internal void DisplayEmployeeDetails(){
4 Console.WriteLine("Employee Name --> Onlinebuff and Employee Code --> 009");
5     }
6 }
In above the code we have class “Employee” with “internal” method “DisplayEmployeeDetails” which displays employee details.

Protected Internal Access Modifier:

The protected internal keyword is a member access modifier.
Protected Internal members are accessible within the same namespace scope in which it is declared or it is accessible in same assembly or same project and it is also accessible in another assembly or project if protected internal member is declared in base class (Parent class) of first assembly then it is also accessible in derived class (child class) of other assembly if access takes place through derived class type.
We can declare protected internal access modifier to a class, method, property, structure, interfaces.
1 public class Employee
2 {
3    protected internal void DisplayEmployeeDetails(){
4     Console.WriteLine("Employee Name --> Onlinebuff and Employee Code --> 009");
5    }
6 }
In above the code we have class “Employee” with “internal” method “DisplayEmployeeDetails” which displays employee details.
So this is all about the access modifiers in csharp if you have any doubts or query please let me know through your comments.

Preview photo after selecting in file input

/* ====== style for file input ======================================= */

.custom-file-input {
    color: transparent;
}

.custom-file-input::-webkit-file-upload-button {
    visibility: hidden;
}

.custom-file-input::before {
    content: ‘Select Photo’;
    color: black;
    display: inline-block;
    /*background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);*/
    background-color: #FFB606;
    border: 1px solid #999;
    border-radius: 3px;
    padding: 10px 8px;
    outline: none;
    white-space: nowrap;
    -webkit-user-select: none;
    cursor: pointer;
    text-shadow: 1px 1px #fff;
    font-weight: 700;
    font-size: 10pt;
}

.custom-file-input:hover::before {
    border-color: black;
}

.custom-file-input:active {
    outline: 0;
}

.custom-file-input:active::before {
    background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);

}

/* ======== style for file input ======================================= */







     
      Clear
     


     







//======== JavaScript ================================================

//variables
var $PhotoInput = $(“#PhotoInput”), $ClearPhoto= $(“#ClearPhoto”);
var $PhotoPreview=$(‘#PhotoPreview’); // img tag

//initially hide img tag.
$PhotoPreview.hide(); $ClearPhoto.hide();

//Handling file change event.
$(“#PhotoInput”).change(function () {
    PreviewPhoto(this); //Calling function to show preview of selected image.

});

//Function to show image preview.
function PreviewPhoto(input) {
      if (input.files && input.files[0]) {
            var photoSize = input.files[0].size;
            photoSize = photoSize / 1024;
            if (photoSize > 600) {
                    ClearPhoto(); //Clearing image if any.
                    $ClearPhoto.hide();
                    alert(‘Please select smaller photo less than 600KB in size’);
            }
            else {
                    var reader = new FileReader();

                    reader.onload = function (e) {
                        $PhotoPreview.attr(‘src’, e.target.result);
                        $PhotoPreview.show();
                        $ClearPhoto.show();
                    }
                    reader.readAsDataURL(input.files[0]);
            }
      }
}

//function to clear img
function ClearPhoto() {
      $PhotoInput.replaceWith($PhotoInput.val(”).clone(true));
      $PhotoPreview.hide();
      $PhotoPreview.attr(‘src’,’#’);

}
//======== JavaScript ================================================

Query String Encryption in ASP.NET

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace QueryStringEncryption
{
    public static class MyCrypto
    {
        private static string Key = “ANY_STRING_VALUE”;
        private static byte[] GetByte(string data)
        {
            return Encoding.UTF8.GetBytes(data);
        }

        private static byte[] EncryptString(string data)
        {
            byte[] byteData = GetByte(data);
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
            algo.Key = GetByte(Key);
            algo.GenerateIV();

            MemoryStream mStream = new MemoryStream();
            mStream.Write(algo.IV, 0, algo.IV.Length);

            CryptoStream myCrypto = new CryptoStream(mStream, algo.CreateEncryptor(), CryptoStreamMode.Write);
            myCrypto.Write(byteData, 0, byteData.Length);
            myCrypto.FlushFinalBlock();

            return mStream.ToArray();
        }

        private static string DecryptString(byte[] data)
        {
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
            algo.Key = GetByte(Key);
            MemoryStream mStream = new MemoryStream();

            byte[] byteData = new byte[algo.IV.Length];
            Array.Copy(data, byteData, byteData.Length);
            algo.IV = byteData;
            int readFrom = 0;
            readFrom += algo.IV.Length;

            CryptoStream myCrypto = new CryptoStream(mStream, algo.CreateDecryptor(), CryptoStreamMode.Write);
            myCrypto.Write(data, readFrom, data.Length – readFrom);
            myCrypto.FlushFinalBlock();

            return Encoding.UTF8.GetString(mStream.ToArray());
        }

        public static string GetEncryptedQueryString(string data)
        {
            return Convert.ToBase64String(EncryptString(data));
        }

        public static string GetDecryptedQueryString(string data)
        {
            byte[] byteData = Convert.FromBase64String(data.Replace(” “, “+”));
            return DecryptString(byteData);
        }

    }
}

C# Date Format

string[] InputDateFormatsAllowed = {
                                            “d/M/yy”, “d/M/yyyy”,
                                            “d/MM/yy”, “d/MM/yyyy”,
                                            “d/MMM/yy”, “d/MMM/yyyy”,
                                            “dd/M/yy”, “dd/M/yyyy”,
                                            “dd/MM/yy”, “dd/MM/yyyy”,
                                            “dd/MMM/yy”, “dd/MMM/yyyy”,

                                            “d-M-yy”, “d-M-yyyy”,
                                            “d-MM-yy”, “d-MM-yyyy”,
                                            “d-MMM-yy”, “d-MMM-yyyy”,
                                            “dd-M-yy”, “dd-M-yyyy”,
                                            “dd-MM-yy”, “dd-MM-yyyy”,
                                            “dd-MMM-yy”, “dd-MMM-yyyy”,

                                            “d.M.yy”, “d.M.yyyy”,
                                            “d.MM.yy”, “d.MM.yyyy”,
                                            “d.MMM.yy”, “d.MMM.yyyy”,
                                            “dd.M.yy”, “dd.M.yyyy”,
                                            “dd.MM.yy”, “dd.MM.yyyy”,
                                            “dd.MMM.yy”, “dd.MMM.yyyy”
                                        };