Something weird seems to have happened with C# classes - c#

I used to be able to do this:
public class Something
{
public class SomethingElse
{
public static class ThisThing
{
public static string aoidj {get;set;}
}
}
}
But it no longer works.
My desired result (and what I've always been able to do) is:
Something.SomethingElse somethingElse = new Something.SomethingElse();
somethingElse.ThisThing.aoidj = "yay";
Console.WriteLine(somethingElse.ThisThing.aoidj);
But that no longer works. Instead of being able to access ThisThing from somethingElse, it's now appearing in SomethingElse.!
Has the C# language changed or something? The behaviour is definitely different and I don't know when it changed.

You need to do this:
Something.SomethingElse.ThisThing.aoidj = "yay";
Console.WriteLine(Something.SomethingElse.ThisThing.aoidj);
Or otherwise change your code to this:
public class Something
{
public class SomethingElse
{
public Whatever ThisThing = new Whatever();
public class Whatever
{
public string aoidj {get;set;}
}
}
}
And then you could do this (your desired result):
Something.SomethingElse somethingElse = new Something.SomethingElse();
somethingElse.ThisThing.aoidj = "yay";
Console.WriteLine(somethingElse.ThisThing.aoidj);

It has to appear in the SomethingElse., otherwise, how can you acces it, it is a Nested Type!
C# has not changed in this way. Nested Types have always been accessible through their parent types.
See my answer here: Cannot access nested classes or members of base class.
Besides, there is no point in having static classes as a Nested Type, since static classes are more commonly used as managers or providers, so they are mainly used elsewhere in your system.
Aside, if you want to access your static class members, you have to type in its name and access it once and for all.
Something.SomethingElse.ThisThing.aoidj
But I can't do that. It would be bad. I need to do it from somethingElse. Not SomethingElse.
Than make it a property rather than a class.
public class Something {
public class SomethingElse {
public OrEventSomethingElse ThisThing { get; set; }
}
}
public class OrEventSomethingElse {
public string aoidj { get; set; }
}
This way, you shall not be able to access it through your Nested Type SomethingElse, but rather through only an instance.
Some resources to help you understand OOP.
Object-Oriented Programming (C# and Visual Basic)
C# Tutorial - An Object Oriented Approach to Programming
Introduction to C# classes
C#.Net Tutorial 17-1 - Classes and Object-Oriented Programming (Part 1)
.NET Tutorial : Object Oriented Programming Using C# For Beginners - Part 1 - Introduction
Beginning C# Object-Oriented Programming
Object Oriented Programming using C# (DOWNLOAD FREE)
** I need it to be a class though, because there is more stuff to go inside of ThisThing**
Make it a class outside of SomethingElse so that you may access it as a simple instance member/property.
public class ThisThing {
public string Stuff { get; set; }
public int SomeMoreStuff { get; set; }
public DateTime EvenMoreStuff { get; set; }
// ...
public string ThisClassIsGettingHuge {
get {
return "Time to refactor because big classes tend to break SRP";
}
}
}
public class Something {
public class SomethingElse {
public ThisThing ThisThingAsAProperty { get; set; }
}
}
It is then, and only then that you shall only be able to access your instance.
var somethingElse = new Something.SomethingElse;
Console.WriteLine(somethingElse.ThisThingAsAProperty.ThisClassIsGettingHuge);
I have developed information and process for years, and I rarely use Nested Types. They generally cause more damage than they help.

Nothing is changed, but your code is wrong. And luckily I found answer too.
class Something
{
public class SomethingElse
{
public SomethingElse()
{
}
public static class sm
{
public static void set()
{
}
}
}
}
Use the class in this manner-
Something.SomethingElse.sm.set();

Related

Add an extra property to an element without inheritance

I am thinking about the best practice in OOP for the following problem:
We have a program that is working with an external API.
The API has an object of type Element which is basically a geometric element.
Our application is a validation application that runs on a geometric model
The application takes a collection of those elements and performs some geometric tests on them.
We wrap this API element with our own class called "ValidationElement" and save some additional information to this wrapper element that can not be obtained directly from the API Element but is required by our application.
So far so good, but now the application should expand and support other types of models (basically we can say that the app is running in a different environment).
Specifically for this environment (and it does not apply to the previous cases), we want to save an additional parameter that obtaining it results in low performance.
What is the best practice option to implement it?
On one hand, I would like to avoid adding extra parameters that are not relevant to a specific(the first) part of the program.
And on the second hand, I am not sure that I want to use inheritance and split this object just for this small additional property.
public class ValidationElement
{
public Element Element { get; set; }
public XYZ Location {get; set;}//The extra property
}
The first and easy option is that the same class will have the additional property and calculation method:
public class ValidationElement
{
public Element Element { get; set; }
public XYZ Location {get; set;}//The extra property
public string AdditionalProperty { get; set; }
public void HardProcessingCalcOfAdditionalProperty()
{
//hard processing
AdditionalProperty = result
}
}
The second option that I mentioned is the inheritance
public class SecondTypeValidationElement : ValidationElement
{
public string AdditionalProperty { get; set; }
public void HardProcessingCalcOfAdditionalProperty()
{
//hard processing
AdditionalProperty = result
}
}
What do you think is the best practice for this? Is there any other way or design pattern that should help me achieve the goal?
I would like to avoid adding extra parameters that are not relevant to a specific(the first) part of the program.
It looks like it is a sign that an inheritance shoulbe be avoided here. As there is a strong possibility that this behaviour is not applicable for other classes.
And this is the second reason to avoid of creation some abstraction:
Element which is basically a geometric element
Because:
all derived elements will have these additional properties.
there are many articles which show how Liskov substitution principle can be violated in geometry figures
So let's prefer composition over inheritance.
So, in my view, it would be really good if we move all heavy, tightly coupled logic of calculating of additional property to separate class:
public class ValidationElement
{
public string Element { get; set; }
public SomeExtra AdditionalProperty { get; set; }
}
public class SomeExtra
{
public string Location { get; set; }//The extra property
public string AdditionalProperty { get; set; }
public void HardProcessingCalcOfAdditionalProperty()
{
//hard processing
AdditionalProperty = string.Empty;
}
}
Why have we created separate class SomeExtra and put logic here:
if we want to edit logic HardProcessingCalcOfAdditionalProperty, then we will edit just one class SomeExtra. By doing this we are satisfying Single Responsibility Principle of SOLID principles.
we can easily create some base abstract class for SomeExtra and then at runtime we can decide what concrete implementation should be injected. By doing this we are satisfying Open Closed Principle of SOLID principles.
UPDATE:
I really like this answer about whether inheritance or composition should be chosen:
My acid test for the above is:
Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is
expected? Indicates Inheritance.
e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class /
both and make it a member of both classes.
Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov
Substitution Principle as a test for 'Should I be inheriting from
this type?'
OOP and SOLID best practice is to use abstractions (interfaces or abstract classes), wich is closer to your second approach.
Dependency Inversion Principle:
The Dependency Inversion principle
states that our classes should depend upon interfaces or abstract
classes instead of concrete classes and functions.
Your first approach to edit the ValidationElement class is generally a bad idea, given that there are several environments for the project to be run onto.
In addition, maintaining and developing the project on this approach is not scalable and will be a headache in the long run.
Open-Closed Principle: The Open-Closed Principle requires that classes should be open for extension and closed to modification.
I suggest below designing:
public interface IValidationElement
{
Element Element { get; set; }
XYZ Location {get; set;}//The extra property
// declare other base properties and methods
}
public class ValidationElement: IValidationElement
{
public Element Element { get; set; }
public XYZ Location {get; set;}//The extra property
// define other base properties and methods
}
public interface ISecondTypeValidationElement: IValidationElement
{
string AdditionalProperty { get; set; }
void HardProcessingCalcOfAdditionalProperty();
}
public class SecondTypeValidationElement: ISecondTypeValidationElement
{
public string AdditionalProperty { get; set; }
public void HardProcessingCalcOfAdditionalProperty()
{
//hard processing
AdditionalProperty = result
}
}
public interface IThirdEnvironmentValidationElement: IValidationElement
{
string ThirdProperty { get; set; }
void RequiredProcessing();
}
public class ThirdEnvironmentValidationElement: IThirdEnvironmentValidationElement
{
public string ThirdProperty { get; set; }
public void RequiredProcessing()
{
//related operations
}
}
I am not going to repeat Open-close, DI, or other principals. It is already discussed. I would look at something like this, or even alternatively use Extensions to setup the value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// old updated
public class Element
{
public Element(string msg) { Message = msg; }
public string Message;
}
public class XYZ { }
public class ABC { }
// new
public interface IDoesSomething
{
void SetResult();
}
// create 2 different wrappers
public class ValidationElementWrapper : IDoesSomething
{
public ValidationElementWrapper(Element el)
{
Element = el;
}
public Element Element { get; private set; }
public XYZ Location {get; set;}
public void SetResult()
{
Console.WriteLine("This is " + Element.Message);
// Do nothing
}
}
public class ValidationElementWrapper2 : IDoesSomething
{
public ValidationElementWrapper2(Element el)
{
Element = el;
}
public Element Element { get; private set; }
public XYZ Location {get; set;}
public string AdditionalProperty { get; set; }
public void SetResult()
{
AdditionalProperty = "Set additional property on wrapper 2";
Console.WriteLine("This is " + Element.Message + " and it has additional property - " + AdditionalProperty);
}
}
// run your program
public class Program
{
public static void Main()
{
var list = new List<IDoesSomething>();
list.Add(new ValidationElementWrapper(new Element("Element 1")));
list.Add(new ValidationElementWrapper2(new Element("Element 2")));
list.ForEach(item => item.SetResult());
}
}
Output
This is Element 1
This is Element 2 and it has additional property - Set additional property on wrapper 2
Alternatively, you can start with more basic class and then keep extending it
public class ValidationElementWrapper : IDoesSomething
{
public ValidationElementWrapper(Element el)
{
Element = el;
}
public Element Element { get; private set; }
public XYZ Location {get; set;}
public virtual void SetResult() // <--- virtual
{
// Do nothing
Console.WriteLine("This is " + Element.Message);
}
}
public class ValidationElementWrapper2 : ValidationElementWrapper // <-- inheritnce
{
public ValidationElementWrapper2(Element el) : base(el)
{
}
public XYZ Location {get; set;}
public string AdditionalProperty { get; set; }
public override void SetResult() // <--- override
{
AdditionalProperty = "Set additional property on wrapper 2";
Console.WriteLine("This is " + Element.Message + " and it has additional property - " + AdditionalProperty);
}
}
Result will be the same

Inner class within Interface in C#

The following question shows how to implement an interface that contains a class in java:
inner class within Interface
The code in Java is:
public interface A {
class B {
}
}
I was hoping the same thing was possible in C#, though I haven't yet been able to get anything working.
For reference, I have a class which makes lookups of key values, but the keys aren't named in a way that makes them easy to understand. I'd like to have a compile time lookup for keys, so the interface would be something like:
interface Lookup {
class Keys {
string SomeKey() => "0"
}
}
Which means I suppose I have two questions:
Is it possible to have an interface containing a class?
Is there a better way of having a lookup between two strings (or any other values) that I can reference reliably at compile time?
Simply put no you can't have a class inside an interface.
From your comments you are talking about having a restricted list of available strings for the keys so I'm wondering if you are in fact not looking for a string/string lookup but just want a convenient way of referencing a list of fixed strings. So a class with constants is all you need:
public static class Strings
{
public const string AString = "A";
public const string BString = "B";
public const string CString = "C";
}
Accessed like this:
var s = Strings.AString;
You cannot have an class within an interface in C#. Interfaces are very simple in C#, and only provide a contract of functionality.
If you want to have a mapping between two strings, a Dictionary<string, string> may be of use to you.
An interface can't itself have any instance data. It's implementation however can have any instance data it requires.
For example, a random example that might give you some insight:
public class SomeClass
{
public string Key {get; set;}
}
public interface ISomeInterface
{
string Value { get; set; }
SomeClass SomeClass { get; set;}
}
public class SomeInterfaceImplementation : ISomeInterface
{
public SomeInterfaceImplementation()
{
SomeClass = new SomeClass()
{
Key = "ABC"
};
}
public string Value { get; set; }
public SomeClass SomeClass { get; set; }
}
public class Program
{
public static void Main()
{
var example = new SomeInterfaceImplementation()
{
Value = "A value",
} as ISomeInterface;
Console.WriteLine($"{example.SomeClass.Key} has value '{example.Value}'");
}
}
In the example, the default constructor "generates" a key of ABC. We could implement this any way your logic requires. But you also have a contract that requires "SomeClass" and it's key is present.
Anywhere you want to use the contract, just accept the Interface and not an implementation class.
Additionally, feel free to play with the fiddle:
Most of the answers under this question are no longer true.
Since C# 8.0, when default interface methods were added, it is possible for an interface to have member declaration that declare for example nested type.
The following code is correct for C# 8.0:
public interface IA
{
class B
{
}
}

every entity implement interface?

Currently, am working on architecture of application, I have many entities in my project i.e student teacher university, I was wondering about is it a good practice that all entity must implement interface. This will help me in dependency injection? What is the best practice from architecture point of view.
public interface IMyEntity
{
//an empty interface
}
public class Student:IMyEntity
{
}
public class Teacher:IMyEntity
{
}
//hi I can deal with every object which implement IMyEntity
void Display(IMyEntity entity) //this function can be in some class
{
// if IMyEntity is teacher behave like a teacher
// if IMyEntity is student behave like sutdent
}
I know interface is a contract, but from architecture point of view it is best practice? I know my IMyEntity interface is empty.
Not necessarily. If in this case Student and Teacher have some common functionality then a shared interface would be one approach to take.
public void Display(IUniPerson person)
{
var name = person.Name; // Everyone, student or teacher, has a name
...
}
However, the example you give seems to suggest that this is not the case, and the Display method will attempt to treat the passed in instance of IMyEntity differently depending on it's type. In that case, you may be better with 2 Display methods with different parameters.
public void Display(ITeacher teacher) { // teacher processing }
public void Display(IStudent student) { // student processing }
tl:dr version: implement an interface across multiple classes if it makes sense for those classes to implement related methods and functions, rather than just as a blanket rule.
I think that decoupling 2 or more classes is a good taste in terms of developing and it really helps maintaining the code in a long run.
Consider the follow scenario:
static void Main(string[] args)
{
var objA = new A();
var objB = new B(objA);
}
public class A {}
public class B
{
public B(A obj)
{
//Logic Here
}
}
The problem with this code it's that it's strongly coupled, class B needs class A to be instanced and do it's business.
This is not a problem if you are sure that B is never going to have some drammatic change.
Now if we want to decouple it we can make a first improvement implementing an interface like
static void Main(string[] args)
{
var objA = new A();
var objB = new B(objA);
}
public interface IA()
{
//TODO
}
public class A : IA {}
public class B
{
public B(IA obj)
{
//Logic Here
}
}
It looks quite better what we still have a couplation problem in the Main, so at this point we will have to implement a Dependency Injection with a IOC like Ninject, and our code will be like to something like:
static void Main(string[] args)
{
var objB = new B();
}
public interface IA()
{
//TODO
}
public class A : IA {}
public class B
{
public B(IA obj)
{
//Logic Here
}
}
Yes, that looks good. We have completely removed the couplation problem and it will be quite easy if in the future we just need to take A, delete it and replace it wich something new more cool.
Obviously overkilling it's a bad practice and I belive DI must be used only after carefuly planning to avoid useless implementations.
For example if I have a class C which has some basic operations, and I am sure that it will never change or have some drammatic need to update i can avoid DI.
So do you have to implement interfaces on every model in your project?
Well I don't think each model in your project needs to implements an interface or DI, just think about it and see where it can be useful and where it's just overkilling.
Looking at how .NET solved this, you can see some ambiguity.
For instance for every object has a function where you can ask for a string representation of the object: ToString(), even though for a string representation might not be a meaningful thing for a lot of classes
On the other hand, although it would be a useful function for every object to make a clone of itself they decided not to let every class implement ICloneable.
Whether it is wise for you to have (almost every) objects of your application a common interface depends on what you will do with this interface and the advantage of all objects implementing such an interface versus the burden of being obliged to implement the interface.
For example, if the entities you are talking about are database records, then it is very likely that every class will have some kind of ID. You could consider giving every class an interface with one get property that returns the value of the ID of the record.
public interface IID
{
long ID {get;}
}
The advantage are multifold:
You encourage every designer of database classes to implement the same type of primary key (in this case a long), and the same property name
Advantage: it is easier to spot the ID of a record
Advantage: it is easier to change the type of the ID
Advantage: you know if you have a database record, you know some of the functions the record must have, without really knowing the type of the record.
Even if the designer needs a different type, or different name, he can still create a special function to implement the interface:
public class Person : IID
{
public int ID {get; set;}
IID:ID {get {return this.ID;} }
}
However, I suggest not to force interfaces to object for which it is not natural to have them. This has the advantage that you can't use these strange functions for object that have no real usage for them.
For example, most classes that represent some ordered numerical value have some notion of addition. Not only for integers and real numbers, but also for classes that represent a time span: 4 days and 23 hours + 1 day and 7 ours = 6 days and 6 hours. So for a time span addition is a useful interface
However, for a date, addition is not meaningful: 4th of july + 14 juillet = ?
So: Yes, implement interfaces for items that are natural to them. They force common naming and enable reuse. No, don't implement them for items that do not have a natural meaning for the functions.
Yes do it like this, it is the best practise. This gives you the advantage of polymorphism. You should do it in better way in current context is not good, because Student is not a Teacher. If you want to share common interface you should define it as: IUniversityMember. Here an example for your case which I think will make it clear.
public interface IUniversityMember
{
//... here common fields between `Teacher` and `Student`
string Name{ get; set;}
string Gender { get; set;}
}
//after that
public interface IStudent
{
int GetGPA();
int CreditsToPass {get; private set;}
}
public interface ITeacher
{
int WorkedHours {get; set;}
decimal PayPerHour {get; private set;}
}
public class BiologicalStudent: IUniversityMember, IStudent
{
public int CreditsToPast {get; private set;}
public BiologicalStudent ()
{
CreditsToPast = 5;
}
//stuff
public int GetGPA()
{
return 3;
}
}
public class MathStudent: IUniversityMember, IStudent
{
public int CreditsToPast {get; private set;}
public BiologicalStudent ()
{
CreditsToPast = 9;
}
public int GetGPA()
{
return 2;
}
}
public class BiologicalTeacher: IUniversityMember, ITeacher
{
public int WorkedHours { get; set;}
public decimal PayPerHour {get; private set;}
public MathTeacher()
{
PayPerHour = 8;
}
}
public class MathTeacher: IUniversityMember, ITeacher
{
public int WorkedHours { get; set;}
public decimal PayPerHour {get; private set;}
public MathTeacher()
{
PayPerHour = 10;
}
}
//Now if you have a university class
public class OxfordUniversity:IUniversity //can inherit interface too
{
public int MinGAPForSchollarship {get; private set;}
public OxfordUniversity()
{
MinGAPForSchollarship = 3;
}
public decimal PaySallary(ITeacher teacher)
{
return teacher.WorkedHours*teacher.PayPerHour;
}
public bool CheckForSchollarship(IStudent student)
{
int gpa = student.GetGPA();
//do some checks
if(gpa >= MinGAPForSchollarship)
return true;
return false;
}
}

Setting Custom Values on Extended class

Im not sure if it is possible. I am running into a unique issue dealing with a clients api.
I am needing to extend a class and add a bool property that does not exist in the base class.
below is an example of what I am trying to accomplish.
public class baseClass
{
//.. No Editable Access
}
public class Extended
{
public bool flaggedAsDeleted(this baseClass bc)
{
//Idealy was looking for get; set; but I know that don't work
return true;// Need to know if possible to set property on baseClass or Alternative
}
public void flagAsDeleted(this baseClass bc)
{
flaggedAsDeleted = true;
}
}
public class program
{
public void doit()
{
baseClass bc = new baseClass();
bc.flagAsDeleted();
}
}
If you're trying to actually extend a class, you do it like this:
public class BaseClass
{
//.. No Editable Access
}
public class Extended : BaseClass
{
public bool FlaggedAsDeleted { get; set; }
}
If you're trying to add data to an existing class, you have two options:
Inheritance - as seen above.
Encapsulation - create a new object that holds an instance of the type you're adding to.
C# provides a feature called Extension Methods, which allows you to seemingly add methods to existing classes. However, these are really just syntactic sugar, as you're still constrained to the class's public API.
public class BaseClass
{
public int Value { get; set; }
}
public static class ExtensionMethods
{
public static void Increment(this BaseClass b)
{
b.Value += 1;
}
}
Extension methods do not allow you to add data to an existing class though.
This is not unique. This is a common problem solved using a Design Pattern called decorator.

Issue with using get keyword in C# relating to inheritance

So I am having some issues with this. I am kinda new to C#. All my attributes are private and I am using the traditional get and set. It is an abstract class. But in the child class when I try and use it in another method, the compiler says cannot use as a method. However if I do the C++ way of accesors and mutators it works fine. Is there a way around this?
Thanks very much for your help
Never mind I got it. I have just been coding for like 7 hrs straight to get this assignment done for school and my brain isn't working right lol thanks very much though
This would be the standard C# way of doing what (I think) you're asking.
public abstract class Base
{
// Automatic Property
public string Prop1 { get; set; }
// With backing field
private string prop2;
public string Prop2
{
get { return prop2; }
set { prop2 = value; }
}
}
public class Derived : Base
{
public string Prop3 { get; set; }
}
public class AnotherClass
{
void Foo()
{
var derived = new Derived();
// Can get and set all properties
derived.Prop1 = derived.Prop1;
derived.Prop2 = derived.Prop2;
derived.Prop3 = derived.Prop3;
}
}

Categories

Resources