Sunday, October 28, 2007

Overloading = Operator in C# implicit

We can’t directly overload = operator in C#. for doing this we should use implicit operator.
consider the following example

class Student
{
    public Student() { }
    int _RegNo;
    private string _StudentName;
    public int RegNo
    {
        get { return _RegNo; }
        set { _RegNo = value; }

    }
    public string StudentName
    {
        get { return _StudentName; }
        set { _StudentName = value; }
    }
}
Student std = new Student();
std = "Crack";//Cannot implicitly convert type 'string' to 'Student'


following example demonstrates an implicit conversion operator, so add following method to Student class

public static implicit operator Student(string name)
{
        Student std = new Student();
        std.StudentName = name;
        std.RegNo = -1;
        return std;
}
Student std = new Student();
std = "Crack";//It will work


Consider another Example ,
    Student std1 = new Student();

    std1.StudentName = "Crack It";

    string studentName = std1;//Error Cannot implicitly convert type 'Student' to 'string'
then we will add another method .
public static implicit operator string(Student std)
{
        return std.StudentName;
}

 

No comments: