I have classes as follow one is SuperClass which is inherited by ChildClass and Child1Class
public class SuperClass
{
public new int Superclassprop = 2;
public virtual void play()
{
Console.WriteLine("SuperClass");
}
}
public class ChildClass : SuperClass
{
public new int Childclassprop = 2;
public override void play()
{
Console.WriteLine("ChildClass");
}
}
public class Child1Class : SuperClass
{
public new int Childclassprop = 3;
public override void play()
{
Console.WriteLine("Child1Class");
}
}
Now when i create an object something like below i don't understand what is the difference between these. i had read a huge bunch of blogs related to this but i didn't find any justifiable answer please help me to understand what actually is happening here or suggest me a good blog or article including on SO where i can understand a whole concept behind this why we need this where the actual real time use of these concept?
SuperClass obj = new SuperClass();
SuperClass obj1 = new ChildClass();
I have attached screenshot of watch which is generating on Run-Time why there is a obj1 consisting all properties but i can access only SuperClassprop?
Thanks in advance any help will be really appreciated.
Here is the more practical example of your topic:
using System;
public class Music
{
public virtual string play()
{
return "Play Music";
}
}
public class Drum : Music
{
public override string play()
{
return "Play Drums";
}
}
public class Piano : Music
{
public override string play()
{
return "Play Piano";
}
}
public class PlayMusicService
{
private readonly Music _musicContext;
public PlayMusicService(Music musicContext)
{
this._musicContext = musicContext;
}
public string PlayAlbum()
{
return _musicContext.play();
}
}
public class Program
{
public static void Main()
{
string whatPlayed = "";
Drum drums = new Drum();
PlayMusicService music1 = new PlayMusicService(new Drum());
whatPlayed = music1.PlayAlbum();
Console.WriteLine(whatPlayed);
Piano piano = new Piano();
PlayMusicService music2 = new PlayMusicService(new Piano());
whatPlayed = music2.PlayAlbum();
Console.WriteLine(whatPlayed);
}
}
Output:
Play Drums
Play Piano
i don't understand what is the difference between these.
One of the main differences is the constructor call
SuperClass obj = new SuperClass();
SuperClass obj1 = new ChildClass();
In the case of obj1 the ChildClass constructor is called after the SuperClass constructor and the field and property initialisation is done also for the property Childclassprop
consisting all properties but i can access only SuperClassprop?
The variable obj1 is still of type SuperClassprop so at compile time you are only allowed to see and use those variables that belong to this class. If you want to actually access the variables of ChildClass you will have to cast it to the proper type:
var r = (obj1 as ChildClass).Childclassproput;
why we need this where the actual real time use of these concept?
One scenario that comes to my mind is : it might be that at compile time it is not clear which class has to be instantiated. But this is decided at runtime. But you need already a variable to write the call of the specific play() method. At runtime it will be decided which method is called in the end.
SuperClass obj = new SuperClass();
bool condition = false;
if (condition)
{
obj = new ChildClass();
}
else
{
obj = new ChildClass1();
}
// now just call the method and the proper method will be called
obj.play();
Related
I recently decided to make a command console for my game, and then proceeded to make some groundwork. My issue is I cannot use it to change any relevant variables, as I have gotten stuck trying to get references to the classes where said variables are stored.
I have an abstract class for my command:
public abstract class Command
{
public abstract void Execute(string[] args);
}
Then I have a class deriving from above class for my command
public class RunesAdd : Command
{
public override void Execute(string[] args)
{
int number;
if(args.Length == 1 && int.TryParse(args[0], out number))
{
Debug.Log(number);
RunCtr.runes += number;
}
else
{
ConCtr.addLogEntry("Incorrect syntax, correct syntax is: runes.add <runes>");
}
}
}
and finally my registry of commands
public class CommandRegistry
{
private Dictionary<string, Command> _commands;
public CommandRegistry()
{
_commands = new Dictionary<string, Command>();
}
public void RegisterCommand(string name, Command command)
{
if (_commands.ContainsKey(name))
{
Debug.Log("Created command already exists");
}
_commands[name] = command;
}
public void RegisterAllCommands()
{
RegisterCommand("testcommand", new TestCommand());
RegisterCommand("runes.add", new RunesAdd());
}
public bool ExecuteCommand(string commandName, string[] args)
{
if (_commands.ContainsKey(commandName) == false)
return false;
_commands[commandName].Execute(args);
return true;
}
}
My problem is that I am unable to get a reference to my class with the variable for runes. I first tried to get a reference to the class in the Command class, so that those variables would be available in all children, but in order to do that I must make a method to actually assign those references, which would look like this:
public void GetReferences()
{
controllerObject = GameObject.FindGameObjectWithTag("Controller Object");
RunCtr = controllerObject.GetComponent<Runes_Controller>();
ConCtr = controllerObject.GetComponent<Console_Controller>();
}
The issue here is that since I cannot get a reference the Command class (due to it being abstract) in any of my monobehavior scripts which have the void Start() method, I cannot actually execute this method to assign the references. I then tried to make another class called GetReferences, which looks like this:
public class GetReferences
{
public GameObject controllerObject;
public Runes_Controller RunCtr;
public Console_Controller ConCtr;
public void GetReferencesMethod()
{
controllerObject = GameObject.FindGameObjectWithTag("Controller Object");
RunCtr = controllerObject.GetComponent<Runes_Controller>();
ConCtr = controllerObject.GetComponent<Console_Controller>();
}
}
Then I made the Command class derive from my GetReferences class, called the GetReferencesMethod() from a monobehavior script on start. Doing this I no longer get an error for not having assigned my classes to references, but whenever I try to edit the values it just does nothing. I have been searching the web for 2 hours now, but no dice. If I explained myself poorly please let me know. Any help is much appreciated, and thanks in advance!
Ok from what I understand is that you are trying to get your Command class using the GetComponent<> method. I might be wrong on this, so correct me if I am wrong.
If it is, then the issue is GetComponent<> only works with MonoBehaviour derived classes. Meaning you have to implement your class as a MonoBehaviour, which should be as simple as this:
public abstract class Command : MonoBehaviour {...}
EDIT
After reading your comments I believe you can use of the a Singleton pattern.
If you place your RuneController & CommandController on the same object and add another class called GameManager or InGameManager.
Then you can use a singleton pattern to access it.
public class GameManager
{
public GameManager Instance { get; private set; }
public RuneController RuneController { get; private set; }
public CommandController CommandController { get; private set; }
void Awake ()
{
// If there is an instance, and it's not me, delete myself.
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
void Start()
{
this.RuneController = GetComponent<RuneController>();
this.CommandController = GetComponent<CommandController>()
}
}
So the usage will look as follow:
GameManager.Instance.RuneController.Execute(command);
I'm experiencing a sort of bug in Unity, probably due to the fact I'm almost new to it:
I have a MonoBehaviour object that correctly lives in memory.
For sake of code organization, this object have two members of standard System.Object classes which needs to be created by a new call.
class A
{
// ...
}
class B
{
// ...
}
class Status : MonoBehaviour
{
A m_AVar;
B m_BVar;
public A AVar
{
get {return m_AVar;}
protected set { m_AVar = value; }
}
public B BVar
{
get { return m_BVar; }
protected set { m_BVar = value; }
}
void Awake()
{
// SingletonImplementation
}
void Start()
{
m_AVar = new A();
m_BVar = new B();
}
At some point in the game someone decides to call my Status.ExecuteSomeAction():
public void ExecuteSomeAction()
{
AVar.DoSome();
BVar.DoSomethingElse();
}
and everything go fine. While at the end by a UIButton.OnClickEvent:
public void ExecuteOnClickAction()
{
AVar.Foo();
}
But no matter what AVar result null. Reading left and right I have the feeling that there's something under the hood with those System.Object which I still don't get.
Where am I doing wrong?
I had a similar problem myself some time ago.
When the singleton pattern creates a new instance of this class (Status) then the links to the UI-Objects won't be created.
To solve this problem create a class which is responsible for handling the UI. This class will then call your Status class.
Another way is to change the singleton pattern to your needs. In my case I simply wrote this:
public static Status Instance { get; set; }
public Awake()
{
Instance = this;
}
This may be a bit sloppy because I will get problems if there is more than one instance of this class but it does the job.
var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName
I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#
Yes, you can use Namespace aliases:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/using-namespaces
using ShortName = Class1.Subclass1.Subclass2;
And then
var test = ShortName.PropertyNameWhichIsBigName;
How about a function:
Func<typeOfProperty> someName = () => Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName;
if you now call
var test = someName();
you would get your desired value without having to type the long chain of properties all the time.
Edit:
Just to be clear, if PropertyNameWhichIsBigName changes, someName() will return the new value.
You can use namespace aliasing and just call it in namespaces section in your code, and you can effectively use objects and functions all over the body #canton7 has already written example for that.
or you can use code blocks statements but you have to implement IDisposable, but this can limit your object calling section but you can get benefit fit automatic dispose.
class Class1
{
public class Subclass1
{
public class Subclass2 : IDisposable
{
public string PropertyNameWhichIsBigName { get; set; }
public void Dispose()
{
throw new NotImplementedException();
}
}
}
}
class Program
{
static void Main(string[] args)
{
using (Class1.Subclass1.Subclass2 obj = new Class1.Subclass1.Subclass2())
{
string propertiesValue = obj.PropertyNameWhichIsBigName;
}
}
}
I am trying to store objects that are only a subclass of an Abstract Class. However, I can only see the abstract class methods and none of the subclass methods. What have I missed?
Class with Error in:
class CharacterStats
{
private Dictionary<StatType, Stat> playerStats;
//Contructor for new game
public CharacterStats()
{
playerStats = new Dictionary<StatType, Stat>();
//Creates all Stats with default values
playerStats.Add(StatType.STA, new StatSta());
playerStats.Add(StatType.STR, new StatStr());
playerStats.Add(StatType.DEX, new StatDex());
playerStats.Add(StatType.DEF, new StatDef());
}
//Returns the damage reduction in %
public int GetDamageReduction()
{
playerStats[StatType.DEF]. //Missing Methods from StatDef class
//Added to remove error message
return 1;
}
}
Abstract Class:
abstract class Stat
{
protected int pointsAdded;
protected int pointCap;
public Stat() {}
public string TestMethod()
{
return "Working!";
}
}
Subclass:
class StatDef : Stat
{
public StatDef() : base()
{
this.pointsAdded = 0;
this.pointCap = 100;
}
public int ApplyDamageReduction(int dmg)
{
//removed data to read easier
return 1;
}
}
Thanks
The type of the expression playerStats[StatType.DEF] is just Stat. The compiler doesn't know what kind of Stat is stored as the value there.
If it will always be a StatDef, then you should just cast:
var def = (StatDef) playerStats[StatType.DEF];
// Now you can use def.ApplyDamageReduction etc
However, you'll need to cast any time you want to use a stat-specific member. Unless you often want to treat multiple stats in the same way, I'd suggest ditching the dictionary approach and just having separate fields:
class CharacterStats
{
private StatDefence defence;
private StatAttack attack;
private StatStrength strength;
// etc
}
You could easily write a method that allows you to iterate over all the stats for the times where that is useful:
public IReadOnlyList<Stat> GetAllStats() =>
new Stat[] { defence, attack, strength, ... };
But my suspicion is that most of the time you're using the stats, you actually want to know a specific stat. I'd always rather write:
var strength = stats.Attack;
than
var strength = stats[StatType.STR];
even if when I don't need the specific aspects of the strength statistic.
I'm working on very simple Roguelike game (just for myself) and get a question:
As it is not possible to create a cross-class struct-object (entity in the game case) that could be accessible from any class of my program, what to use to create a cross-class object? I was thinking of something like storing all newly created object (enities) in a static object array, but I guess there is more simple solution on this problem.
Question itself: How to create a cross-class accessible object(s) with your own properties?
Thanks everybody, I found what I was searching for.
It seems like you tried passing around a value type (a struct) between different classes and you noticed that when you update the value in one place it doesn't change the value in another place.
That's the basic difference between value types and reference types.
If you are creating the struct yourself you may want to instead define it as a class.
If not, you could wrap all your structs in a class and pass the class around as your state object.
If all you have is simply a list of the same type of struct (like Points), just pass the List itself around. C# collections are implemented as classes.
public class GameState
{
public Point PlayerLocation { get; set; }
public List<Point> BulletPoints { get; set; }
public double Health { get; set; }
}
Now you can create a GameState and pass it around to different classes:
public class Game
{
private GameState _state = new GameState();
private BulletUpdater _bulletUpdater = new BulletUpdater();
public void Update()
{
_bulletUpdater.UpdatePoints(_state);
// Points have now been modified by another class, even though a Point is a struct.
}
}
public class BulletUpdater
{
public void UpdatePoints(GameState state)
{
for (int i = 0; i < state.BulletPoints.Count; i++)
{
Point p = state.BulletPoints[i];
state.BulletPoints[i] = new Point(p.X + 1, p.Y + 1);
}
}
}
Just remember in the above code if I were to write:
Point p = state.BulletPoints[i];
p.X += 1;
p.Y += 1;
That wouldn't affect the original point! When you read a value type from a list or from a class into only copies the value into a local variable. So in order to reflect your changes in the original object stored inside the reference type you need to overwrite it like so:
state.BulletPoints[i] = p;
This same principal is why the following also will not work:
state.PlayerLocation.X += 5; // Doesn't do anything
state.PlayerLocation.Y += 5; // Also doesn't do anything
The compiler would tell you in this case that you are doing something wrong. You are only modifying the returned value of the property, not the backing field itself. You have to write it like so:
state.PlayerLocation = new Point(state.PlayerLocation.X + 5, state.PlayerLocation.Y + 5); // This works!
You can do the following:
Using IoC Framework, like Ninject. You can setup Ninject to create single instance for all usages.
The other option is to use Singleton pattern design pattern
And the third one is to use static property
It sounds like you want to use the Singleton pattern:
http://en.wikipedia.org/wiki/Singleton_pattern
Here is an example of what this would look like in C#:
public class Singleton
{
static Singleton()
{
Instance = new Singleton();
}
public static Singleton Instance { get; private set; }
}
It's possible. What about public and static class?
public static class CrossClassObject
{
public static object MyProperty { get; set; }
public static void MyMethod() {}
}
Of course this class should be placed in the same namespace that other ones.
How to use it?
class OtherClassInTheSameNamespace
{
private void SomeMethod()
{
var localVariable = CrossClassObject.MyProperty; // get 'cross-class' property MyProperty
CrossClassObject.MyMethod(); // execute 'cross-class' method MyMethod()
}
}
No idea what you are trying to achieve... but if you want a list of objects accessible 'cross-class', just make a static class with a list of objects and then when you reference your class from any other class, you will have access to its list of objects. Here is something like that:
public static class ObjectController
{
private static IList<object> existingObjects;
public static IList<object> ExistingObjects
{
get
{
if (existingObjects == null)
{
existingObjects = new List<object>();
}
}
}
}
public class MyObject
{
public MyObject()
{
ObjectController.ExistingObjects.Add(this);
}
public void Delete()
{
ObjectController.ExistingObjects.Remove(this);
}
}
Then you can add stuff like
MyObject newObj = new MyObject();
//// other stuff... This object should now be visible to whatever other class references ObjectController
newObj.Delete();