C#: Access Enum from another class - c#

I know I can put my enum at the Namespace area of a class so everyone can access it being in the same namespace.
// defined in class2
public enum Mode { Selected, New, }
What I want is to access this enum from
public class1
{
var class2 = new class2();
// Set the Mode
class2.Mode = Model.Selected
}
Is this somehow possible without using namespace area?

You can declare an enum outside of a class:
namespace MyNamespace
{
public enum MyEnum
{
Entry1,
Entry2,
}
}
And then you can add using MyNamespace; where it needs to be used.

Aaron's answer is very nice but I believe there is a much better way to do this:
public static class class1
{
public void Run()
{
class2.Mode mode = class2.Mode.Selected;
if (mode == class2.Mode.Selected)
{
// Do something crazy here...
}
}
}
public static class class2
{
public enum Mode
{
Selected,
New
}
}
No point over complicating this. It is a simple task.
All the Best
Chris.

If you are trying to do what is described below it will not work...
public class MyClass1
{
private enum Mode { New, Selected };
public Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will not work due to protection level
myClass1.ModeProperty = MyClass1.Mode.
}
}
What you could do however is below, which will work...
public interface IEnums
{
public enum Mode { New, Selected };
}
public class MyClass1
{
public IEnums.Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will work
myClass1.ModeProperty = IEnums.Mode.New;
}
}

Yes:
class2.Mode = class2.Mode.Selected
But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile. Either the enum or the property will need to be named something else. Your class name and variable name conflict too, making this a bit more complex.
To make this a more generic answer, if you have this:
public class Foo
{
public SomeEnum SomeProperty { get; set; }
public enum SomeEnum {
Hello, World
}
}
Then this code will assign an enum value to the property:
Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;

I ended up solving my issue by changing it to a namespace accessor, found by utilizing Intellisense. I thought the enum was in the class, not just the namespace. If it was in the class, I would recommend moving it out of the class.
namespace ABC.XYZ.Contracts
{
public class ChangeOrder : BaseEntity, IAuditable
{
...
}
public enum ContractorSignatureType
{
A,
B,
V
}
}
ContractorSignatureType = Contracts.ContractorSignatureType.B,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int)temp.names.nikk);
Console.ReadKey();
}
}
}

//by using this you can access the value of enum.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(temp.names.nikk);
Console.ReadKey();
}
}
}

Related

error CS0116: A namespace cannot directly contain members such as fields or methods- hand writing coding using notepad

Getting the error on line 16, with the foreach. My professor wont email fast enough and the due date is in a few hours! I think I am missing a list or something. I think the d after the double is incorrect. Any help is appectiated!
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class Starbucks
{
public static void Main()
{
double[] x = {4.2, 5.7, 3.6, 9.1, 2.7, 8.4 };
}
}
static void MyGenerics(double x)
{
foreach (double d in x)
{
MessageBox.Show(x);
}
}
That's because you have defined the MyGenerics() method outside the class Starbucks. Move it inside the class. Error message is exactly telling the same thing. Your code should look like
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class Starbucks
{
public static void Main()
{
double[] x = {4.2, 5.7, 3.6, 9.1, 2.7, 8.4 };
MyGenerics(x);
}
static void MyGenerics(double[] xx)
{
foreach (double d in xx)
{
MessageBox.Show(d);
}
}
}
This problem can be caused by bad indentation. For example:
using System;
namespace Interrogacion_1.Model
{
interface IClass
{
public string Name { get; set; }
}
{
Console.WriteLine("HELLO WORLD"); #here error cs0116
}
}
The correct way would be:
using System;
namespace Interrogacion_1.Model
{
interface IClass
{
public string Name { get; set; }
public void Imprimir()
{
Console.WriteLine("HELLO WORLD");
}
}
}

Create new instance of private class in another private class

Is it possible to create an instance of a private class in another private class? (Not counting within the main() program.)
And also, is it possible for a method in a private class to return a private type object?
This question came because I was following Scott Allen from PluralSight on C# Fundamentals With C#5. And on lesson 2 about classes and objects, he has a code example like this:
public GradeStatistics ComputeStatistics()
{
GradeStatistics stats = new GradeStatistics();
...
...
}
with GradeStatistics defined in a separate class file like:
class GradeStatisticss
{
}
Inlined comment: I am not talking about nested classes. What I meant is, you have two classes (separate files) and I am wondering if one class can create an instance of another class (knowing they are both private).
Edited with examples:
private class Example1
{
}
private class Example2
{
public Example1 DoSomeComputation()
{
return new Example1();
}
}
private class Example3
{
Example1 ex1 = new Example1();
}
Is Example3 able to create ex1? Can Example2 return a new instance of Example1?
Is it possible to create an instance of a private class in another private class?
Only if the private class for which you want to create an instance is declared inside the private class that wants to create the instance. If they are not nested, it's not possible.
Is it possible for a method in a private class to return a private type object?
Yes, it can.
Here's some code showing everything together:
public class Tester {
private class ThePrivateCreator {
private class TheOtherPrivateClass {
}
public Object createObject() {
return new TheOtherPrivateClass();
}
}
public void canWeDoThis() {
ThePrivateCreator c = new ThePrivateCreator();
Console.WriteLine(c.createObject());
}
}
class Program
{
public static void Main(string[] args) {
Tester t = new Tester();
t.canWeDoThis();
}
}
No. A private class cannot be accessed by another class in a different file. The reason why is that the modifier private is meant to encapsulate the data or method inside of that class. You should use the public or internal modifier if you want to access a class from a different class that is not nested. If it is nested, you can also use the protected modifier.
Not sure exactly what you had in mind, but here's one possible example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
private1 p1 = new private1();
private2 p2 = p1.foo();
Console.WriteLine(p2.Value);
Console.ReadLine();
}
private class private1
{
public private2 foo()
{
private2 p2 = new private2("I was created inside a different private class!");
return p2;
}
}
private class private2
{
private string _value;
public string Value
{
get { return _value; }
}
public private2(string value)
{
this._value = value;
}
}
}
}

Use a class in two different namespace

How do use a class from namespace in other namespace?
namespace All
{
class X
{
public static void Read() {}
}
class Y
{
public static void Write() {}
}
}
namespace A
{
namespace First{
//use class X in namespace All here;
}
}
namespace B
{
namespace Second{
//use class Y in namespace All here;
}
}
i don't want copy paste code,is there a keyword in C# to reference the hole the class? use it here like
B.Second.Y.Write();
you cannot directly use other types as variable in a namespace
So
You may use those types (X, Y) in the types in those namespaces (First, Second). e.g
namespace All
{
class X
{
public static void Read() { }
}
class Y
{
public static void Write() { }
}
}
namespace A
{
namespace First
{
//use class X in namespace All here;
}
}
namespace B
{
namespace Second
{
//use class Y in namespace All here;
class MyClass
{
private All.X; //HERE is the code
}
}
}
Try the using Keyword
using A;
using B;
using All;
If you define namespace A & B as followed:
namespace All
{
public class X
{
public static void Read() { }
}
public class Y
{
public static void Write() { }
}
}
namespace A
{
namespace First
{
public static class X
{
public static void Read()
{
All.X.Read();
}
}
}
}
namespace B
{
namespace Second
{
public static class Y
{
public static void Write()
{
All.Y.Write();
}
}
}
}
You can then use it like so...
namespace CodeResearch.StackOverFlowTests
{
using System;
/// <summary>
/// Defines DebugStackOverFlow type
/// </summary>
public class DebugStackOverFlow
{
/// <summary>
/// Tests debugging StackOverFlow questions
/// </summary>
public static void Test()
{
A.First.X.Read();
B.Second.Y.Write();
Console.ReadLine();
}
}
}
NOTE:
I have all of this defined in the same cs file.

How to call function inside custom attribute class

Lets say i have the following attribute class.
//Attribute Implementation
public abstract class TestAttribute : Attribute
{
public abstract void UpdateSomething(string s);
}
public class CustomAttTest : TestAttribute
{
private State state;
public CustomAttTest(State state)
{
this.state = state;
}
public override void UpdateSomething(string s)
{
if (state.Equals(State.First))
{
Console.WriteLine("First State!! " + s);
}
}
}
public enum State
{
First, Second, Third
}
How can i call the Updatesomthing function inside the attribute class?
following is the attribute implementation example.
public abstract class Vehicle
{
//Coode
}
[CustomAttTest(State.First)]
public class Ferrari : Vehicle
{
//Code
}
Here is the full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var foo = new Ferrari();
//How do i call the UpdateSomething implemented insde the CustomAttTest attribute class?
}
}
public abstract class Vehicle
{
//Coode
}
[CustomAttTest(State.First)]
public class Ferrari : Vehicle
{
//Code
}
//Attribute Implementation
public abstract class TestAttribute : Attribute
{
public abstract void UpdateSomething(string s);
}
public class CustomAttTest : TestAttribute
{
private State state;
public CustomAttTest(State state)
{
this.state = state;
}
public override void UpdateSomething(string s)
{
if (state.Equals(State.First))
{
Console.WriteLine("First State!! " + s);
}
}
}
public enum State
{
First, Second, Third
}
}
You need to use reflection:
foo.GetType().GetCustomAttribute<CustomAttTest>().UpdateSomething(...);
However, you should probably use an abstract method or property instead of an attribute.

c#: Calling common method of stored references to class objects from object[] array

Is using a switch on object types really the main way of calling a common function of stored references to class objects? It doesn't have to be a 'object' value type.
using System;
public class MainClass { public void Main() { print "hello world"; } }
public class SubClassOne : MainClass { }
public class SubClassTwo : MainClass { }
public class Storer
{
public void Main() {
object[] objects = new object[2];
objects[0] = new SubClassOne();
objects[1] = new SubClassTwo();
for(i=0;i<2;i++)
{
switch(objects[i].GetType().ToString())
{
case: "SubClassOne":
SubClassOne subclass = objects[i];
subclass.Main();
break;
case: "SubClassTwo":
SubClassTwo subclass = objects[i];
subclass.Main(); //Could probably call after the switch
break;
}
}
}
}
Note: Code not parsed, so there may be serious errors.
"Stringly" typed object oriented code is such a bad idea. You (almost) never need to know the type of an object via a string.
Changing your "print" to Console.WriteLine and main to this works fine
MainClass[] stuff = new MainClass[2];
stuff[0] = new SubClassOne();
stuff[1] = new SubClassTwo();
foreach(var item in stuff)
{
item.Main();
}
If the problem is you are determined to use an array of object, AlexH has answered.
In that case, I suggest to use as keyword to perform a safe cast operation :
using System;
public class MainClass { public void Main() { print "hello world"; } }
public class SubClassOne : MainClass { }
public class SubClassTwo : MainClass { }
public class Storer
{
public void Main() {
object[] objects = new object[2];
objects[0] = new SubClassOne();
objects[1] = new SubClassTwo();
for(i=0;i<2;i++)
{
var myMainClass = objects[i] as MainClass;
if (myMainClass != null)
{
myMainClass.Main();
}
}
}
}
As wudzik said it should be even better to declare objects as a MainClass array
There are many ways of solving this in a nice way, depends on:
If you know types and there are not too much of them:
Use LINQ OfType<>(). For more details see MSDN
foreach (var item in objects.OfType<SubClassOne>())
{
item.Main();
}
foreach (var item in objects.OfType<SubClassTwo>())
{
item.Main();
}
If there are many types, just introduce common interface
interface ISharedApi
{
void Main();
}
class SubClassOne : ISharedApi
class SubClassTwo : ISharedApi
And implement this/mark each type by it, then you just need single loop:
var objects = new List<ISharedApi>();
objects.Add(new SubClassOne());
objects.Add(new SubClassTwo());
foreach (var item in objects)
{
item.Main();
}
You should implement a more object oriented solution. Instead of creating an array consisting of objects you should make MainClass abstract and define an abstract method Main. After that you should implement Main in you sublclasses.
In this way you can exchange your code to:
using System;
public abstract class MainClass { public abstract void Main(); }
public class SubClassOne : MainClass {
public override void Main() { print "SubClassOne, hello world"; }
}
public class SubClassTwo : MainClass {
public override void Main() { print "SubClassTwo, hello world"; }
}
public class Storer
{
public void Main() {
MainClass[] objects = new MainClass[2];
objects[0] = new SubClassOne();
objects[1] = new SubClassTwo();
foreach(MainClass mc in objects)
{
mc.Main();
}
}
}

Categories

Resources