0
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

1
  • 3
    We can't possibly know the intention - we have no idea what that method is meant to do, or where you found it, or who the author was. You'll need to give more context, at the very least. Commented May 5, 2013 at 6:14

5 Answers 5

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);
    }
}

Comments

0

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.

Comments

0

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.

Comments

-1

(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);

1 Comment

Read carefully. The question is not about constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.