Reputation: 51
public class SampleCass{
public void DoSomething(SampleCass sample){
//Do method implementation
}
}
In the above code sample, the method parameter type passed is same as the class to which the method belongs to. I wanted to know why it is done this way and also some details on it
Thanks in advance
Upvotes: 0
Views: 398
Reputation: 247
That's because that method uses an instance of that class other than its own to do something. Imagine you have a Contact type and a method that compares it to another contact. You can make this:
public class Contact
{
public string name;
public bool Compare(Contact c)
{
return this.name.Equals(c.name);
}
}
Upvotes: 2
Reputation: 48558
(I am giving a constructor example, which will help you in understanding non-constructor methods.)
This can be used to create copy constructor like
public class SampleCass
{
public int MyInteger { get; set;}
//Similarly other properties
public SampleClass(SampleClass tocopyfrom)
{
MyInteger = tocopyfropm.MyInteger;
//Similarly populate other properties
}
}
can can be called like this
SampleClass copyofsc = new SampleClass(originalsc);
Upvotes: -1
Reputation: 2684
Well, there can be many uses depending upon your problem domain. I can give you another example where you can write fields of same type as of the class.
eg:
public class Node
{
public Node _next;
}
I know your question is very particular but I thought this example can add value to the current question.
Upvotes: 0
Reputation: 431
If I had to guess, I would say it is done this way, because logic inside method uses two instances of the object - one upon which method is called (this), and one passed trough the parameter (sample). If logic inside method does not use both instances of the object, something might be done wrong.
Hope this helps, for more details we need to see more code.
Upvotes: 0
Reputation: 12423
This can have may uses. Consider for instance a Number class (dumb):
public class Number {
private readonly int _n = 0;
public Number(int n) { _n = n; }
public Number Add(Number other) {
return new Number(this._n + other._n);
}
}
Upvotes: 2