Mohammad yummy
Mohammad yummy

Reputation: 111

How to create an object and use it into other methods of a class in C#

I'm trying to write a class which needs to use an object in the other method of the class, consider the Pseudo code :

class socket {

private (something to be used by other methods) interface_like_method {
//initializing a socket class
//to be used by other methods
}

public FileTrasfer (ref socket client) {
// here, we can use the initialized obj of interface_like_method 
// client.sendfile("a path") ; 
}
}

How such the functionality could be implemented?

Upvotes: 0

Views: 103

Answers (1)

Abdul Ahmad
Abdul Ahmad

Reputation: 10021

declare a variable as an 'instance variable' (also known as 'member variable'). This means that this variable can be used anywhere in the class. If the variable is declared inside a method, only that method has access to it.

class One {
//code
}

class Two {
 One one; //instance variable accessible in entire class, not initialized
 One oneInitialized = new One(); //this one is initialized
 Two() { //this is a constructor
  one = new One(); //initializes the object 'one' that is declared above
 }
 someMethod() {
  One secondOne = new One(); //can only be used inside this method
 }
 //use object 'one' anywhere;
}

Upvotes: 3

Related Questions