I have tried making the field public itself; I have also tried using public get, even if, as I understand, access modifiers inside a property will only have effect if more restrictive. Yet I wasn't able to access the 'problem.Points'(last line) property from the TestUnit. I get an "get accessor inaccessible" alert. Notice that I'm able to access it from another class in the same namespace. I must be missing something very basic here.
namespace Coordinates_Path
{
public interface IProblem
{
abstract public List<Node> Points { get; set; }
abstract public Object GetStartState();
abstract public bool IsGoalState();
abstract public Object GetSuccessor();
}
public class ShortestPathThroughCoordinates : IProblem
{
private Node startState;
private List<Node> points;
public List<Node> Points { get { return points; } private set; }
//...
//...
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Coordinates_Path;
using System.Linq;
using System.Collections.Generic;
namespace CoordPathTest
{
[TestClass]
public class KruskalTest
{
[TestMethod]
public void TestMST()
{
// ...
IProblem problem = new ShortestPathThroughCoordinates("P1", coordDic);
MSTKruskal kruskal = new MSTKruskal(problem.Points)
If you look at
public class ShortestPathThroughCoordinates : IProblem
{
public List<Node> Points { get { return points; } private set; }
...
all referenced classes must be visible to the calling assembly. Check to ensure that Node is also visible.
Change your interface to this:
public interface IProblem
{
List<Node> Points { get; set; }
Object GetStartState();
bool IsGoalState();
Object GetSuccessor();
}
Interfaces only define public members so you do not have to declare it. All members of an interface must be implemented so there is also no need to declare them as abstract.
Unless private List points; is set somewhere further down in the code that we can't see you are never initializing this variable so your get will be null;
Related
Sorry I'm kinda new to c# how would I make a class where I can access it like this:
Myclass.subclass.method();
This is what I have now:
namespace zzcore
{
class myclass
{
class subclass
{
public static void method() { }
}
}
}
What happens here is that a nested class without a visibility modifier is implicitly private. In this context, private means that only the parent class can see it.
Declare both classes as public and you will be able to call myclass.subclass.method();
namespace zzcore
{
public class myclass
{
public class subclass
{
public static void method() { }
}
}
}
Working example: http://ideone.com/tJVKJ
So I have a base class that has many children. This base class defines some readonly properties and variables that have default values. These can be different, depending on the child.
Readonly properties/fields allow you to change the value of the variable inside the constructor and also the definition, but nowhere else. I get a 'readonly variable can only be assigned to in a constructor' error if I try to change the value of an inherited readonly variable in the child class' constructor. Why is this and how can I work around this, without Reflection?
My intention: To allow user extensibility through scripts where they can only change certain fields once.
The reason is that you can only assign to readonly fields in the constructor of that class.
According to the definition of readonly in the C# Reference (emphasis mine):
When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
To work around this, you could make a protected constructor in the base that takes a parameter for the readonly property.
An example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Child();
Console.WriteLine(b.i);
Console.Read();
}
}
class Base
{
public readonly int i;
public Base()
{
i = 42;
}
protected Base(int newI)
{
i = newI;
}
}
class Child : Base
{
public Child()
: base(43)
{}
}
}
Adam has the right answer. If you're worried about the space it will take up (number of parameters in the constructor?) then you should address that as a different problem with a different solution: create a BaseConfig class, that contains all those properties and that is all that needs to be passed in. Base can then either assign all it's readonly fields from BaseConfig's properties, or you can instead have Base hold just one readonly field of type BaseConfig and refer to that for the values.
As to why this is, see C# constructor execution order regarding when each class's readonly fields would be initialized/initializable.
You could get the exact behavior you are looking for by using virtual get only properties.
public class BSE
{
virtual public int Prop
{
get
{
return 6;
}
}
}
public class Derived : BSE
{
public override int Prop
{
get
{
return 10;
}
}
}
Fields are out side the inheritance and overloading model and should not be used to provide polymorphic features.
You can use property with public get accessor and protected set accessor. Derived classes can set value of this property.
An example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Child();
Console.WriteLine(b.I);
Console.Read();
}
}
class Base
{
public int I { get; protected set; }
public Base()
{
I = 42;
}
}
class Child : Base
{
public Child()
{
I = 43;
}
}
}
this is impossible by design. try passing the values to a protected base class constructor
I have a need where I have to add some new fields to an existing class along with all its existing fields/attributes.
So whenever my derived class is filled by DAL, I will be filling all fields of base class as well. Currently, I am doing it like this but not sure this is the right way ? Please give me an example. Also I am not sure whether the base class object will be a new one each time a derived class is initialized ?
public class Employee
{
private int _id;
private int _name;
public int ID
{
set { _id=value;}
get { return _id;}
}
public int Name
{
set { _name=value;}
get { return _name;}
}
protected void SetName ()
{
_name=value;
}
protected void SetID()
{
_id=value;
}
}
public class EmployeeWithDepartmentName:Employee
{
private string _deptName;
public string DeptName
{
set { _deptName=value; }
}
public setBaseEmpName()
{
base.SetName();
}
public setBaseID()
{
base.SetID();
}
}
Everything in a base class can automagically be accessed from derived classes without doiing anything, just use the property/method name directly.
public class MyBase
{
public string UserName {get;set;}
}
public class MyClass : MyBase
{
public void DoSomething()
{
Console.WriteLine("UserName: {0}", UserName);
UserName = "Anders";
}
}
You can also do this:
MyClass myClass = new MyClass();
myClass.UserName = "Rune";
Protected means that only derived classes can access the property/method. Public means that everyone can access the properties/methods.
Also I am not sure whether the base class object will be a new one each time a derived class is initialized ?
It's not two objects, it's one object created from two different classes (that's how inheritance works).
Read this article about inheritance: http://www.csharp-station.com/Tutorials/lesson08.aspx
I have a name space Company.Controls, which contains several controls. I also have a class called "Common" which contains enums/structures/static methods that I use throughout the controls.
Is there a way to make these "Common" peices belong to the Company.Controls namespace this way I don't have to keep typing "Common.Structure"? Essentially having he "Common" both a namespace and a class.
Just seems messy and confusing when reading the code.
example (all the other controls are in the Blah.Controls.Common namespace)
namespace Blah.Controls
{
public enum ControlTouchState
{
Down = 0x00,
Up = 0x01,
}
public Common()
{
//Stuff here
}
}
Thanks.
You can't get exactly what you want; in C# all methods have to be in a class.
Depending on what is in your Common class, you might be able to find something a slightly more satisfying by using extension methods:
namespace Blah.Controls
{
public class CommonControl { }
public static class Common
{
public static void Foo(this CommonControl cc) { }
}
public class Control1 : CommonControl
{
public void Bar()
{
this.Foo();
}
}
}
Another thing you might consider is using partial classes which would let you write simple wrappers elsewhere:
namespace Blop.Controls
{
public static class Common
{
public static void Foo() { }
}
public partial class Control1
{
public void Bar()
{
Foo();
}
}
public partial class Control1
{
public void Foo()
{
Common.Foo();
}
}
}
Obviously, introducing some inheritence could eliminate some of the duplication; I'm assuming you don't want to do that.
Is there some reason that the nested types in Common MUST be nested? Why not separate them out into their own namespace?
namespace Common
{
public struct Structure
{
// ...
}
public enum Enumeration
{
// ...
}
public class Common
{
// ...
}
}
You could then use the Common namespace as such:
namespace Blah.Controls
{
using Common;
class Control
{
Struct myStruct;
Enumeration myEnum;
Common myCommon; // references the class, not the namespace
}
}
I'm using the Unity dependency injection framework.
I have two classes, that each take the same delegate parameter in the constructor. Each class should get a different method when resolved.
Can I set this up without using attributes ? If not how would you do it with attributes?
Yep, you can decorate properties or constructor parameters with the [Dependency] attribute.
This example isn't using delegates, it's just using an interface instead, but it shows two of the same interface being registered with different names, and a class requesting a particular one in its constructor:
[TestClass]
public class NamedCI
{
internal interface ITestInterface
{
int GetValue();
}
internal class TestClassOne : ITestInterface
{
public int GetValue()
{
return 1;
}
}
internal class TestClassTwo : ITestInterface
{
public int GetValue()
{
return 2;
}
}
internal class ClassToResolve
{
public int Value { get; private set; }
public ClassToResolve([Dependency("ClassTwo")]ITestInterface testClass)
{
Value = testClass.GetValue();
}
}
[TestMethod]
public void Resolve_NamedCtorDependencyRegisteredLast_InjectsCorrectInstance()
{
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ITestInterface, TestClassOne>("ClassOne");
container.RegisterType<ITestInterface, TestClassTwo>("ClassTwo");
container.RegisterType<ClassToResolve>();
var resolvedClass = container.Resolve<ClassToResolve>();
Assert.AreEqual<int>(2, resolvedClass.Value);
}
}
[TestMethod]
public void Resolve_NamedCtorDependencyRegisteredFirst_InjectsCorrectInstance()
{
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ITestInterface, TestClassTwo>("ClassTwo");
container.RegisterType<ITestInterface, TestClassOne>("ClassOne");
container.RegisterType<ClassToResolve>();
var resolvedClass = container.Resolve<ClassToResolve>();
Assert.AreEqual<int>(2, resolvedClass.Value);
}
}
}
Instead, you could try passing a factory in on the constructor of the objects. That way you can guarantee (and test) in code exactly what objects are created.