Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am making a game that has several classes and each one do some kind of specific task.
I am completely new to OOP and I was wondering what I should do to make my class instances communicate between each other without recurring to static classes, methods and properties, which seems like an awful thing to do.
I am self-taught programmer, and I realize I do a lot of bad practices. So far I managed to make this work making both classes static but I wanted to know what I should do to make my code as good as possible.
Also, it would be nice if you could recommend me some resources/books/articles so I can read more about this topic (communcation between instances).
Here is some piece of code so you understand what I am talking about.
class Program
{
static void Main(string[] args)
{
Class1 instance1 = new Class1();
Class2 instance2 = new Class2();
// infinite loop
while (true)
{
instance1.UpdateMethod(someValue);
instance2.UpdateMethod();
}
}
}
class Class1
{
int Property;
UpdateMethod(int argument)
{
Property += argument;
if(Property == 3000)
{
// I should change the state of instance2
}
}
}
class Class2
{
UpdateMethod()
{
if(Time.GetTime() == SomeTime)
{
// here I want to change the state of instance1
}
}
}
For an overview of common design patterns, I recommend
http://en.wikipedia.org/wiki/Category:Software_design_patterns
If there is a natural relationship between Class1 and Class2, it's quite common for an instance of one to hold a reference to an instance of another. For example, if you have a Player class, and the player has a Weapon, define your class like this:
public class Player
{
public Weapon Weapon { get; set; }
// Other properties
}
Specifically in your case, it looks like you want to update an instance of Class1 from an instance of Class2. I would suggest that you define a property on Class2 that holds the related instance of Class1, just as in the example above.
This is called the Composite Pattern.
In software engineering, the composite pattern is a partitioning
design pattern. The composite pattern describes that a group of
objects are to be treated in the same way as a single instance of an
object. The intent of a composite is to "compose" objects into tree
structures to represent part-whole hierarchies. Implementing the
composite pattern lets clients treat individual objects and
compositions uniformly.
Another pattern frequently used to act on an object instance is the Command Pattern.
In object-oriented programming, the command pattern is a design
pattern in which an object is used to represent and encapsulate all
the information needed to call a method at a later time. This
information includes the method name, the object that owns the method
and values for the method parameters. Three terms always associated
with the command pattern are client, invoker and receiver. The client
instantiates the command object and provides the information required
to call the method at a later time. The invoker decides when the
method should be called. The receiver is an instance of the class that
contains the method's code. Using command objects makes it easier to
construct general components that need to delegate, sequence or
execute method calls at a time of their choosing without the need to
know the owner of the method or the method parameters.
I would suggest you two links and the content their is free to read
http://msdn.microsoft.com/en-us/library/dd460654.aspx
A bit more on patterns with better details is http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep
and final one from uncle bob good explanation on OOD Principles http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
If you need to change the state of an object from another class, you need a reference to it. Common ways to do this are through the constructor:
public class Class2
{
private readonly Class1 instance;
public Class2(Class1 instance)
{
this.instance = instance;
}
public void UpdateMethod()
{
if(VisualStyleElement.TaskbarClock.Time.GetTime() == SomeTime)
{
// here I want to change the state of instance1
this.instance.SomeProperty = "Some Value";
}
}
}
or through a parameter passed into the method
public class Class2
{
public void UpdateMethod(Class1 instance)
{
if (VisualStyleElement.TaskbarClock.Time.GetTime() == SomeTime)
{
// here I want to change the state of instance1
instance.SomeProperty = "Some Value";
}
}
}
In the first case you would call it like this:
Class2 instance2 = new Class2(instance1);
instance2.UpdateMethod();
And in the second case you would call it like this:
Class2 instance2 = new Class2();
instance2.UpdateMethod(instance1);
Be most welcome to the world of OOP!
One important thing to understand is the notion of inheritance. Inheritance regards to what is. A Child is a Person, and a Mother is a person.
Please, take a look at this model:
public class Person
{
protected string Name;
public string WhatsYourName()
{
return this.Name;
}
}
public class Mother: Person
{
public Mother(string personName)
{
this.Name = personName;
}
}
public class Child : Person
{
public Mother MyMother { get; set; }
public Child(string personName)
{
this.Name = personName;
}
public string WhoAreYou()
{
return string.Format("My name is {0} and my mom is {1}", this.Name, this.MyMother.WhatsYourName());
}
}
Now, how do objects talk to each others? There are plenty of ways to achieve this, but it all comes to a simple concept: references.
When you create an object (x = new ...) you are creating a new instance, and you have its reference.
Now, look at this:
static void Main(string[] args)
{
Mother mary = new Mother("Mary");
Child bobby = new Child("Bobby");
bobby.MyMother = mary;
Console.WriteLine(bobby.WhoAreYou());
Console.ReadLine();
}
See when we are setting Bobby's mother? We are passing its object reference.
Please, take a look at this code, I believe it can help.
Further on, I'd strongly recommend you to read about design patterns.
Maybe starting here: http://www.dofactory.com/Patterns/Patterns.aspx/
Hope this helps.
It all depends on what Class1 and Class2 are and if they need to be coupled or not.
If they do unrelated things and do not need to know about each other, you can use events to communicate changes between them:
class Program
{
static void Main(string[] args)
{
Class1 instance1 = new Class1();
Class2 instance2 = new Class2();
instance1.CriticalValueReached += instance2.DoSomething;
instance2.TimeoutElapsed += instance1.DoSomething;
// infinite loop
while (true)
{
instance1.UpdateMethod(someValue);
instance2.UpdateMethod();
}
}
}
class Class1
{
int Property;
public event Action CriticalValueReached;
public UpdateMethod(int argument)
{
Property += argument;
if (Property == 3000)
RaiseCriticalValueReached();
}
public void DoSomething()
{
// Whatever...
}
private void RaiseCriticalValueReached()
{
var handler = CriticalValueReached;
if (handler != null)
handler();
}
}
class Class2
{
public event Action TimeoutElapsed;
public UpdateMethod()
{
if (Time.GetTime() == SomeTime)
RaiseTimeoutElapsed();
}
public void DoSomething()
{
// ...
}
private void RaiseTimeoutElapsed()
{
var handler = TimeoutElapsed;
if (handler != null)
handler();
}
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Let's say I have the following inheritance tree:
______ Object______
/ \
Food Material
/ \ / \
Egg Carrot Box Axe
Expressed like this in C#
class Object { ... }
class Food : Object { ... }
class OfficeMaterial : Object{ ... }
class Box : OfficeMaterial { ... }
class Spoon : OfficeMaterial { ... }
class Egg : Food { ... }
class Carrot : Food { ... }
And now I want to share the functionality only between the class Box and Egg, for instance:
bool opened = true;
public void Open() { open = true; }
public void Close() { open = false; }
public bool IsOpen() { return opened; }
This is a short example, but it could be something much longer.
What would be the proper way to do it? If I use inheritance, other classes like Carrot and Axe will get it, which is something I do not wish.
UPDATE
Many people mention Composition. Could someone show me how that would work in the example I presented?
You have a few options:
Use interfaces
Ex:
public interface IOpenable
{
void Open();
void Close();
bool IsOpen();
}
Then any class that needs the openable/closable behavior can implement the interface accordingly.
Favor composition over inheritance and compose your objects out of other objects that implement the desired behavior.
Why not use an interface? IOpenable?
interface IOpenable {
void Open();
void Close();
bool IsOpen();
}
When I think about the similarities between Egg and Box that are not properties shared by Carrot and Axe I think first about the fact that they contain something.
Egg and Box have Contents which can be exposed, hidden, added, removed, etc.
Notice the language here - Egg and Box have Contents. The word have (or has) is an indicator that an object representing the Contents of another object should be used as a composition element.
An Egg is a type of Food. An Egg has Contents which are a Yolk and an EggWhite.
A Box is a type of OfficeMaterial. A Box has Contents which are OfficeSupplies.
I could write something like this:
public class Food : Object
{
public void Eat() { }
}
public class OfficeMaterial : Object { }
public class Contents : Object
{
bool _visible = false;
List<Object> _things = new List<Object>();
public int Count { get { return _things.Count; } }
public bool IsOpen { get { return _visible; } }
public void Expose()
{
_visible = true;
}
public void Hide()
{
_visible = false;
}
public void Add(object thing)
{
_things.Add(thing);
}
public bool Remove(object thing)
{
return _things.Remove(thing);
}
}
public class Box : OfficeMaterial
{
public Contents BoxContents = new Contents();
}
public class Egg : Food
{
public Contents EggContents = new Contents();
}
Which would further allow me to:
void PlaceEggsInBox(int numEggs, Box box)
{
box.BoxContents.Expose();
if (box.BoxContents.AreVisible)
{
int eggsInBox = box.BoxContents.Things.Count(thing => thing is Egg);
for (int i = 0; i < numEggs - eggsInBox; i++)
{
box.BoxContents.Add(new Egg());
}
}
}
And then I might like to
void EatAllEggsInBox(Box box)
{
box.BoxContents.Expose();
foreach (Egg egg in box.BoxContents.Things.Where(thing => thing is Egg))
{
box.BoxContents.Remove(egg);
egg.EggContents.Expose();
if (egg.EggContents.AreVisible) egg.Eat();
}
}
The Eat() method is a method of the Food class. The Expose() method is a method of the Contents class, not the Food class or the OfficeMaterials class, nor of the Egg nor Box classes.
That's effectively multiple inheritance, which C# doesn't support other than through interfaces.
An option is to create an interface without the Open method (otherwise you'll have to implement it, so this is only for typing purposes) then implement a static extension methods in a static class alongside your interface.
public Interface IOpenable { }
public static class IOpenableExtensions {
public static Open(this IOpenable obj){
// work on any concrete implementation of IOpenable
}
}
Usage:
var box = new Box; // Box implements IOpenable
var egg = new Egg; // Egg implements IOpenable
box.Open();
egg.Open();
This pattern may work well when the actual inheritance reflect a core structure or organization while the interfaces provide common "behaviors" shared by certain objects. A class may implement one or more of such interfaces.
C# 8 default interface implementation might make this pattern more common.
In practice, you often end up needing to cast your objects to the interface when working with functions that deal with your base classes.
public IEnumerable<Food> GetFoods(){ ... }
public void HandleFood() {
for(var food in GetFoods()) {
if(food is IOpenable openableFood){
openableFood.Open();
}
}
}
Finally, note that this is not true multiple inheritance as you cannot inherit/override the extension methods themselves through a hierarchy of interfaces. If you have IOpenableFood inherit IOpenable with both an Open() extension method, you can't call base() in the derived one, and you'll have to choose which extension method to use explicitly. Best to avoid this altogether.
var egg = new Egg(); // Egg inherits both IOpenable and IOpenableFood
egg.Open(); // Error: Ambiguous method
IOpenableFoodExtensions.Open(egg); // OK, call that method
IOpenableExtensions.Open(egg); // OK, call other method
I'm struggling because of this:
My classes have some methods that have temporal coupling. This is, some method MethodA has to be invoked first to "initialize" the data that MethodB needs to work properly.
I usually make the temporal coupling explicit by passing the offending dependency to "MethodB" as argument, like in this snippet:
private class SomeClass
{
private string field;
private int count;
public SomeClass()
{
MethodA();
MethodB(field);
}
private void MethodA()
{
field = "Something";
}
private void MethodB(string str)
{
count = str.Length;
}
}
Although it makes things explicit I feel I'm doing something wrong. I end up having method that don't use fields at all (static methods!), so the class starts to seem less cohesive.
Is this the best way to do it? (losing cohesion by passing arguments)
EDIT: Regarding some answers that suggest using field as a parameter in the constructor or using the Builder Pattern to avoid invalid states: I cannot do that, because in my case I'm building a Parser. MethodA reads the input and sets the state depending on it (reading characters from a file) and then, MethodB is invoked. They have to be invoked in the correct order. That is the real problem: one should be invoked before the other.
If you follow Anemic Domain Model, you can break your class and make it 2 smaller classes. You become aware of bad design because your current class violates SRP, in short it has 2 responsibility: 1 for handle the input process, 1 for process the input result.
Break it down so that ClassA will handle the input and returning result, then ClassB will take the result from ClassA as parameter, then process it. ex:
public class ClassA
{
public string MethodA()
{
// read the input
return "Something"; // or return the input
}
}
public class ClassB
{
private int count;
public void MethodB(string str)
{
count = str.Length;
}
}
If you find the use of both class is bothersome, use another aggregate service for that. ex:
public class ClassC
{
public ClassA ClassA = new ClassA();
public ClassB ClassB = new ClassB();
public void Execute(){
string result = ClassA.MethodA();
ClassB.MethodB(result);
}
}
Fluent API's solve this kind of thing on public interfaces by not exposing dependent methods in the "builder" object until appropriate:
SomeClass someInstance = SomeClassBuilder(x=> {
x.MethodA().MethodB("somevalue");
});
This requires alot more plumbling because you need the builder object, as well as builder components such as an object that is returned from MethodA which exposes MethodB. This way the only way to call MethodB is to first call MethodA.
I'm not encouraging you to take this approach. It's probably overkill for many scenarios, but is important to be aware of this option in case you encounter a scenario where it is appropriate.
I guess you need to have a sort of complex initialization, in which some parameters have to be specified before actually initialize the object, and you want a better control on what the class user is doing to avoid invalid states. A good know pattern to solve such situation is the so called "Builder Pattern", very frequently used in OOP. I don't want to point a particular article, you will find yourself a lot of examples by just using the keyword "builder pattern". Just to be complete, the overall idea is to make a fluent sequence of method specifying values of internal fields, and delegate a final method "Build" to create an working object instance, and validate the parameters passed.
I don't know what is your exact goal, but why not put the parameter in the constructor of the class:
private class SomeClass
{
private string _field;
private int _count;
public SomeClass(string field)
{
_field = field;
_count = field.Length;
}
}
Now you will have something like this
SomeClass sc = new SomeClass("Something");//or whatever you want for field.
You can just remove the parameter from MethodB and use the field, in this way you don't lose cohesion
private class SomeClass
{
private string field;
private int count;
public SomeClass()
{
MethodA();
MethodB();
}
private void MethodA()
{
field = "Something";
}
private void MethodB()
{
count = field.Length;
}
}
Notes:
1) The way you describe the problem seems like Template Method design pattern, you should have a look here.
2) Static methods don't belong to that class
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
An application I'm working on processes Work Items. Depending on the state of a work item there are a number of actions available. "Complete" "Cancel" "Reassign" etc...
To provide the functionality for the actions I currently have an interface that looks something like this...
public interface IActionProvider{
public void Complete(WorkItem workItem);
public void Cancel (WorkItem workItem);
public void Reassign(WorkItem workItem);
}
Then based on other details of the work item I have concrete implementations of the interface. Just for example...
public class NormalActionProvider :IActionProvider
{
...
}
and
public class UrgentActionProvider : IActionProvider
{
....
}
The problem is, if I want to add a new action, say... "Delegate" I have to update the interface which of course has effects on all of the implementations.
Does this violate the Open/Close Principle? Can you recommend a design pattern or refactor that may help me here?
Looks like command pattern would be suitable. You can modify/add more commands. The command classes are decoupled from the main program.
public interface IActionProvider{
public void execute(WorkItem item,ActionType actionType);
}
ActionType represents Complete,Cancel & so on. You can keep adding more action types & plugin appropriate command classes.
You could always add a Decorator to the IActionProvider interface (follow the Decorator design pattern).
It depends on what you really are trying to accomplish with your IActionProvider. If you really want to make it so that every implementation must be able to perform all of the actions that you consider to be important, then that should be a part of the interface that they implement. Interfaces work best if they are well-planned ahead of time so they don't have to change continually.
But it sounds like you don't necessarily want all actions to be implemented by all providers. I'd need to know more details to be able to give good advice, but one example would be to have the providers initialize themselves against a kind of event Bus. They could subscribe to those events that they care about, and perform actions only for the events that make sense for the specific implementation.
"Depending on the state of the workitem", brings the State Design Pattern
One way or another, you'll have to refactor you interface and eventually break client contracts.
If i have understood your problem correctly, then you have a WorkItemProcessor whose state changes depending
on the WorkItem Sent to it.
Therefore your WorkItemProcessor becomes
// Context
public class WorkItemProcessor
{
public IState CurrentState { get; set; }
public WorkItemProcessor(IState initialState)
{
CurrentState = initialState;
}
public void Process(WorkItem workItem)
{
CurrentState.Handle(this, workItem);
}
}
Then we define multiple states that the WorkItemProcessor could potentially be in
// State Contract
public interface IState
{
void Handle(WorkItemProcessor processor, WorkItem item);
}
// State One
public class CompleteState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CompletenessConditionHoldsTrue ? (IState) this : new CancelState();
}
}
// State Two
public class CancelState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CancelConditionHoldsTrue ? (IState) this : new CompleteState();
}
}
Assuming your WorkItem Looks like
// Request
public class WorkItem
{
public bool CompletenessConditionHoldsTrue { get; set; }
public bool CancelConditionHoldsTrue { get; set; }
}
To put it all together
static void Main()
{
// Setup context in a state
WorkItemProcessor processor = new WorkItemProcessor(new CancelState());
var workItem1 = new WorkItem { CompletenessConditionHoldsTrue = true };
var workItem2 = new WorkItem { CancelConditionHoldsTrue = true };
// Issue requests, which toggles state
processor.Process(workItem1);
processor.Process(workItem2);
Console.Read();
}
Hope this gets you closer. Cheers.
I would also choose the command pattern. As an enhancement, you can combine it with the abstract factory method, so you can have a factory class for each command class, and all those factories implement a common factory interface.
For example:
// C#
public interface ICommand { void Execute(); }
public interface ICommandFactory { ICommand Create(); }
public class CommandFactoryManager
{
private IDictionary<string, ICommandFactory> factories;
public CommandFactoryManager()
{
factories = new Dictionary<string, ICommandFactory>();
}
public void RegisterCommandFactory(string name, ICommandFactory factory)
{
factories[name] = factory;
}
// ...
}
This way, you can register new command factories dynamically. For example, you can load a DLL at runtime and fetch all the classes that implement the ICommandFactory interface using reflection, and you have a simple plugin system.
I have 2 cases wheter a method can be considered a Factory Design Pattern, this example is in C#, altought, can apply to other programming languages:
enum NinjaTypes {
Generic,
Katanna,
StarThrower,
Invisible,
Flyer
}
public class Ninja {
public string Name { get; set; }
public void jump() { ... }
public void kickAss() { ... }
}
public class KatannaNinja: Ninja {
public void useKatanna() { ... }
}
public class StarNinja: Ninja {
public void throwStar() { ... }
}
public class InvisibleNinja: Ninja {
public void becomeInvisible() {...}
public void becomeVisible() {...}
}
public class FlyNinja: Ninja {
public void fly() {...}
public void land() {...}
}
public class NinjaSchool {
// always return generic type
public Ninja StandardStudent() {...}
// may return other types
public Ninja SpecialityStudent(NinjaTypes WhichType) {...}
}
The method StandardStudent() always return a new object of the same type, the SpecialityStudent(...), may return new objects from different classes that share the same superclass / base type. Both methods are intentionally not virtual.
The question is, are both methods "Factory Design Pattern" ?
My guess is that SpecialityStudent(...) is, but StandardStudent() is not. If the second is not, can be considered another design pattern ?
I don't think that nor a FactoryMethod`nor AbstractFactory patterns forbid the user to use a parameter to specify a type to the creator method. Anyway you should consider at least 2 things in your design:
Factory methods are useful to keep the client unaware of the concrete type of the created object. From my point of view isn't wrong to specify explicitly the type of object to be created, but pay attention to not put too much knowledge on the client classes to be able to construct objects through the factory.
Both your factory methods return a Ninja object, but some of your ninjas extended class declare additional methods, which client is unaware of. If your client need to use those methods explicitly then maybe you have to make some consideration on your design.
I think this actually looks like an Anti-Pattern. There's really nothing to stop a consumer of this code to just instantiate the specialty ninjas directly. What benefit is there to using the Ninja School? I think the whole point of the Factory pattern is to encapsulate the process of instantiating an object so that you can hide the details from the consumer. Any time you make a change to the "creation" logic, it doesn't break anyone's code.
And it just looks like a bad idea to have all the types in an enum. I don't have a concrete reason to back up this claim other than, "it feels wrong".
After reviewing the Abstract Factory pattern, I can see how you could go about turning this into an Abstract Factory, but I don't see the benefit given the semantics of your objects. I think that if you want to have a Ninja factory, you'd have to make the individual constructors protected or internal, so they can't be called directly by consumer code
Both your methods can be seen as factories. But the second one is a little awkward to use:
var school = new NinjaSchool();
var ninja = school.SpecialtyStudent(NinjaTypes.Flyer);
// to fly you must cast
((FlyingNinja)ninja).Fly();
You've already asked for a flyer, so you shouldn't need to cast. A better option might be to eliminate the enum and ask for the exact ninja that you want:
var flyingNinja = school.FlyingStudent(); // you get a FlyingNinja
flyingNinja.Fly();
Another thing to consider in your design is this: what if you want an invisible ninja that can fly? Or a katana ninja that also throws stars? That will shake up your hierarchy and challenge your belief in inheritance.
It's almost a factory method. I would do something like:
enum NinjaTypes {
Generic, Katanna, StarThrower, Invisible, Flyer
}
class Ninja {
String Name;
void jump() {
}
void kickAss() {
}
void useKatanna() {
System.out.println("nothing happens");
}
void throwStar() {
System.out.println("nothing happens");
}
void becomeInvisible() {
System.out.println("nothing happens");
}
void becomeVisible() {
System.out.println("nothing happens");
}
void fly() {
System.out.println("nothing happens");
}
void land() {
System.out.println("nothing happens");
}
}
class StarThrowerNinja extends Ninja {
void throwStar() {
System.out.println("throwing star");
}
}
class NinjaSchool {
static Ninja create(NinjaTypes WhichType) {
switch (WhichType) {
case Generic:
return new Ninja();
case StarThrower:
return new StarThrowerNinja();
default:
return null;
}
}
}
public class Main {
public static void main(String[] args) {
Ninja generic=NinjaSchool.create(NinjaTypes.Generic);
generic.throwStar();
Ninja starThrower=NinjaSchool.create(NinjaTypes.StarThrower);
starThrower.throwStar();
}
}
I am looking for an algorithm that can get the object that called the method, within that method.
For instance:
public class Class1 {
public void Method () {
//the question
object a = ...;//the object that called the method (in this case object1)
//other instructions
}
}
public class Class2 {
public Class2 () {
Class1 myClass1 = new Class1();
myClass1.Method();
}
public static void Main () {
Class2 object1 = new Class2();
//...
}
}
Is there any way to do this?
Here's an example of how to do this...
...
using System.Diagnostics;
...
public class MyClass
{
/*...*/
//default level of two, will be 2 levels up from the GetCaller function.
private static string GetCaller(int level = 2)
{
var m = new StackTrace().GetFrame(level).GetMethod();
// .Name is the name only, .FullName includes the namespace
var className = m.DeclaringType.FullName;
//the method/function name you are looking for.
var methodName = m.Name;
//returns a composite of the namespace, class and method name.
return className + "->" + methodName;
}
public void DoSomething() {
//get the name of the class/method that called me.
var whoCalledMe = GetCaller();
//...
}
/*...*/
}
Posting this, because it took me a while to find what I was looking for myself. I'm using it in some static logger methods...
You could get to the current stack trace in code and walk up one step.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
But as was commented below, this will get you the method and class calling you, but not the instance (if there is one, could be a static of course).
or just pass the object as method parameter.
public void Method(object callerObject)
{
..
}
and call the Method:
myClass.Method(this);
regards, Florian
It would be very bad style since
a) that would break encapsulation
b) it's impossible to know the type of the calling object at compile-time so whatever you do with the object later, it will propably not work.
c) it would be easier/better if you'd just pass the object to the constructor or the method, like:
Class1 c1 = new Class1(object1);
Obviously i don't know the exact details of your situation but this really seems like you need to rethink your structure a bit.
This could easily be done if proper inheritance is structured.
Consider looking into an abstract class and classes that inherit from said abstract class. You might even be able to accomplish the same thing with interfaces.