I am trying to achieve the namespace hierarchy used in C# in my class library. Here is what I am trying to do:
namespace Parent
{
namespace Child
{
Class ChildClass { }
}
Class ParentClass { }
}
After compiling the class library It did not work as expected. Here is my expected working principle.
To access the ChildClass one has to using Parent.Child. But one can access ParentClass just by using Parent.
I can do this without compiling the class library but adding the cs file to the project. But when I compile as DLL and add it as a reference in a project I can't access the sub-namespaces.
UPDATE: I have different files for each class. When I write all namespaces and classes into one file it seems to work. But why?
Is there anyway to achieve this in C#?
I think your classes missing public; Following code works for me.
namespace Parent
{
namespace Child
{
public class ChildClass { }
}
public class ParentClass
{
}
}
I can create;
Parent.ParentClass p;
Parent.Child.ChildClass c;
Which is your expected working principle.
EDIT: separate cs file for each class approach;
ParentClass.cs
namespace Parent
{
public class ParentClass{ }
}
ChildClass.cs
namespace Parent
{
namespace Child
{
public class ChildClass { }
}
}
This seems to be working for me.
You are nesting classes and namespaces and it all seems a little confused. Why don't you keep a flatter namespace structure and do the nesting in your classes. Keep in mind that you don't need to nest namespaces or classes to maintain a parent child relationship.
Have a read of the following: Parent child class relationship design pattern
This should get you started in the right direction:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
using System;
using System.Collections.Generic;
public class ChildClass
{
private ParentClass parent;
public ChildClass(ParentClass parentIn)
{
parent = parentIn;
}
public ParentClass Parent
{
get { return parent; }
}
}
public class ParentClass
{
private List<ChildClass> children;
public ParentClass()
{
children = new List<ChildClass>();
}
public ChildClass AddChild()
{
var newChild = new ChildClass(this);
children.Add(newChild);
return newChild;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var p = new ParentClass();
var firstChild = p.AddChild();
var anotherChild = p.AddChild();
var firstChildParent = firstChild.Parent;
var anotherChildParent = anotherChild.Parent;
}
}
}
Related
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;
so I have a library Mine.SuperFun which calls stuff in the library SuperFun whose main namespace is SuperFun. The problem i'm having is that i can't address classes or basically anything in the SuperFun library inside classes in the Mine.SuperFun.XyZFoo namespaces
The only way to address them i have is doing stuff like:
using SuperFun_NiceClass = SuperFun.NiceClass;
using Mine.SuperFun {
...
SuperFun_NiceClass.DoStuff()
is there something i can do (besides changing the namespace in Mine library) to be able to address those classes directly?
You can use the global contextual keyword
What is the usage of global:: keyword in C#?
http://msdn.microsoft.com/en-us/library/cc713620.aspx
namespace Mine.SuperFun
{
public class My { public int a; }
}
namespace SuperFun
{
public class Theirs { public int a; }
}
namespace SomeProgram
{
public class Program
{
SuperFun.Theirs theirs;
global::Mine.SuperFun.My mine;
}
}
I'm trying to learn patterns and I'm stuck on determining how or where a Factory Pattern determines what class to instanciate. If I have a Application that calls the factory and sends it, say, an xml config file to determine what type of action to take, where does that logic for interpreting the config file happen?
THE FACTORY
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myNamespace
{
public abstract class SourceFactory
{
abstract public UploadSource getUploadSource();
}
public class TextSourceFactory : SourceFactory
{
public override UploadSource getUploadSource()
{
return new TextUploadSource();
}
}
public class XmlSourceFacotry : SourceFactory
{
public override UploadSource getUploadSource()
{
return new XmlUploadSource();
}
}
public class SqlSourceFactory : SourceFactory
{
public override UploadSource getUploadSource()
{
return new SqlUploadSource();
}
}
}
THE CLASSES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myNamespace
{
public abstract class UploadSource
{
abstract public void Execute();
}
public class TextUploadSource : UploadSource
{
public override void Execute()
{
Console.WriteLine("You executed a text upload source");
}
}
public class XmlUploadSource : UploadSource
{
public override void Execute()
{
Console.WriteLine("You executed an XML upload source");
}
}
public class SqlUploadSource : UploadSource
{
public override void Execute()
{
Console.WriteLine("You executed a SQL upload source");
}
}
}
The actual factory to instantiate is selected at runtime, often by a separate factory loader class. The loader may get the necessary configuration, e.g. in an xml config file, and read from it the class name of the concrete factory to load.
This in itself is not a very complicated logic; the reason to put it into a factory loader class is reusability. You can have many factories in your app, and often, most of the factory loading code is pretty similar, so putting it into a separate class (hierarchy) eliminates code duplication. And of course, the logic may be different and more complicated than this example.
E.g. a more dynamic scenario would be to specify a mapping between buttons / menu items and class names in the xml file, then on the GUI, the user could change the factory to be used by pressing a button / selecting a menu item.
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
}
}
While dividing my C# application in layers, I have solved the problem of circular dependency among layers in the following way:
using System;
using System.Collections.Generic;
using System.Text;
using SolvingCircularDependency.Common;
using SolvingCircularDependency.DA;
namespace SolvingCircularDependency.BO
{
public class MyClass : IPersistent
{
private string _message;
public string Message
{
get { return _message; }
set { _message = value; }
}
public bool Save()
{
return MyClassDA.Save(this);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace SolvingCircularDependency.Common
{
public interface IPersistent
{
bool Save();
string Message { get;}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using SolvingCircularDependency.Common;
namespace SolvingCircularDependency.DA
{
public class MyClassDA
{
public static bool Save(IPersistent obj)
{
Console.WriteLine(obj.Message);
return true;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using SolvingCircularDependency.BO;
namespace SolvingCircularDependency.UI
{
class Program
{
static void Main(string[] args)
{
MyClass myobj = new MyClass();
myobj.Message = "Goodbye Circular Dependency!";
myobj.Save();
Console.ReadLine();
}
}
}
Please take a look at the class MyClassDA in the DA layer and the assembly itself.
How can a MyDA.Get() method return objects of type MyClass when the Data Access layer doesn't know about the MyClass type.
If this design is not efficient, How can I change/modify it?
As far as I can understand you have a bidirectional relationship between your DA and Business layer.
To solve this problem I suggest that you should have 3 layers instead of two. I mean you should have a Model layer that simply model the DB objects ,then you can derive from model classes in your Business layer and add other behaviors like Save method.
Here's what I mean:
//Model Layer
public class UserModel
{
public virtual string Firstname{get;set;}
}
//DataAccess Layer
public class UserDao
{
List<UserModel> GetAll();
}
//BusinessLayer
public class UserDomainModel:UserModel
{
public UserDomainModel(UserModel user,UserDao dao)
{
_user=user;
_dao=dao;
}
public override string FirstName
{
get
{
return _user.FirstName;
}
set
{
_user.FirstName=value;
}
public void Save()
{
_dao.Save(_user);
}
}
}
I'm using a decorator to combine User and UserDao as a domain model object.
One of the reasons people do Persistance Ignorant objects (POCO) is to avoid such a scenario. There is simply no way for the data access layer to have a reference to a class that it doesn't know about - it is much better to have the class not know about the data access.
The only way you can really do this is to implement Get() on User instead of on UserDA. You can do something like this:
public class User {
IGetFromPresistance<User> _userFetcher;
public static IList<User> GetMatching(Specification<User> spec) {
var values = _userFetcher.Find(spec); //Returns a DataRow or IDictionary<string, object>
return new User() {
PhoneNumber = new PhoneNumber(values["phone"].ToString()),
Name = values["name"].ToString(),
};
}
}