How To Access Class A Folder To Be Used In Another Class - c#

I am using C#
Scenario: Same project
FolderA - ClassA
FolderB - ClassB
I have a method in ClassB that needs the methods from ClassA.
How can I do that?

The folder part does not matter, but one common way to expose methods to other classes is to make them public. You can either use static or instance methods.
Ex
public class A
{
public void SomeMethod(){}
public static void SomeStaticMethod(){}
}
public class B
{
public B()
{
A a = new A();
a.SomeMethod();
A.SomeStaticMethod();
}
}
Another alternative is to use inheritance and let class A inherit from class B
public class A : B
{
public A()
{
//you can now call the methods defined in B
base.SomeMethod();
}
}
Above is an example of how to do it.

Related

How to instatiate a derived class instead of its base

This is my problem:
I have a Class A that is used (instantiated) several times within a Class B.
I need to change the behaviour of the Class A, mainly the constructor, and then I derived it with Class C.
Class C: Class A
I would like that Class B using in its methods Class C instead of Class A, avoiding to override all the methods that used it.
Is it this possible?
Many thanks
I was not clear, therefore let me try to explain better with code.
Public Class A
{
`// Simple constructor
public A(params[])
{
// things here
}
}
Public Class C : A
{
// Constructor doing different thing then base
public C(params[]): base(params[])
{
// do different things here
}
}
Public class B
{
public B(params[])
{ }
public method_A(params[])
{
A _temp = new A(params[]);
// do things here with A
}
}
I use B in my program, but I would like that for one istance of B it uses A and for another instance of B it uses C instead of A.
Something like:
Main()
{
B _instance1 = new B();
B _instance2 = new B();
// use instance 1
_instance1.method_A(...);
// use instance 2
_instance2.method_A(...); // do something here for using C instead of A in the method
}
Just instantiate class C in class B and use it as you would class A, it will have the same functions as A with your added logic in class C.
in your constructor it might be worthwhile to do something like:
public class C : A
{
public C() : base()
{
// do stuff
}
}
so that it will also call A's constructor.

C# specific visibility for some methods

I have two classes in a namespace and these classes need to call each other like this:
public class A
{
void MethodVisibleToB() {}
}
public class B
{
void MethodVisibleToA() {}
}
I want the methods to not be seen neither from inside the dll nor from outside. I wanted only class A to see B.MethodVisibleToA and only class B to see A.MethodVisibleToA.
I usually restrain visibility of a method with nested classes, but this time it is not possible as well as unnecessarily complex. Can you suggest a way to prevent this methods to be called from outside?
The options I have now are not that good:
make all public (meh),
make all internal and move A and B in another dll (not doable)
Edit: I forgot to mention that the classes are in the same namespace in the same assembly
Solution: I took Mrinal Kamboj's suggestion and implemented the interfaces explicitly:
internal interface IA
{
void VisibleByB();
}
internal interface IB
{
void VisibleByA();
}
public class A : IA
{
void IA.VisibleByB() { }
}
public class B : IB
{
void IB.VisibleByA() { }
}
Event more pervert solution to a pervert problem: this will prevent the two interfaces and relative methods to be accessed from other classes and even subclasses:
public static class ClassAreNotMeantToBeUsedThisWay
{
interface IA
{
void VisibleByB();
}
interface IB
{
void VisibleByA();
}
public class A : IA
{
void IA.VisibleByB() { }
}
public class B : IB
{
void IB.VisibleByA() { }
}
}
Try using an Interface and implement Explicitly as follows:
interface InterfaceA
{
void MethodVisibleToB();
}
interface InterfaceB
{
void MethodVisibleToA();
}
public class A : InterfaceA
{
void InterfaceA.MethodVisibleToB() { }
}
public class B : InterfaceB
{
void InterfaceB.MethodVisibleToA() { }
}
Access as follows:
InterfaceA a = new A();
a.MethodVisibleToB();
InterfaceB b = new B();
b.MethodVisibleToA();
this way method would be available when wrapped up in an interface type, will not be available when not wrapped in an Interface type, but a class type
You can mark the methods as internal
Internal types or members are accessible only within files in the same assembly
See the following example:
public class A
{
internal void MethodVisibleToB() {}
}
public class B
{
A aInstance = new A();
internal void MethodVisibleToA()
{
aInstance.MethodVisibleToB(); // this can only be called by methods that are within the same assembly as B
}
}
Addendum
If you need to access the method from the outside, you can use InternalsVisibleToAttribute in the assembly where A and B are located. Anyway, I'd recommend this for a very restricted scope only, e.g. (unit-)tests. Place this line in any .cs file in your assembly (without an namespace)
[assembly: System.InternalsVisibleTo("MyAssembly.Tests")]

Need to add same properties in two different classes

I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties. But both Classes have the same set of properties.
My Question is, If I add any new property in Class A, I need to add that in Class B also. If I did not add means, need to show error. How can I achieve this through C#?
You may achieve this by using an Interface and implementing it both in class A and class B. In the interface, define the property that is required in class A and B:
public interface ICommonProperty
{
string MyProperty{ get; set; }
}
Or you can use keyword abstract to create a class in common for A and B.
abstract class BaseClass // Abstract class
{
public int X {get;set;} // property in common for 2 class
}
class A : BaseClass
{
}
class B : BaseClass
{
public int Y {get;set;} // other property of B
}
You can go with the abstract class. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
Here is a simple example related to your question However you can understand and learn about Abstract classes here : Abstract Class
using System;
public class Program
{
public static void Main()
{
A objA = new A();
objA.printA();
B objB = new B();
objB.printB();
}
}
abstract class Parent{
public int a = 5;
}
class A : Parent
{
public void printA()
{
Console.WriteLine("In class A, value is "+a);
}
}
class B : Parent
{
public void printB()
{
Console.WriteLine("In class B, value is "+a);
}
}
Output of the above program is:
In class A, vlaue is 5
In class B, vlaue is 5
Hope this helps you.

What is the difference between a sealed class and a private class? [duplicate]

This question already has answers here:
When and why would you seal a class?
(5 answers)
Closed 2 years ago.
I know that you can not inherit from a class once sealed is used but I am confused what is the difference between these two: private and sealed?
Can't we make the base class members private if we don't want to inherit them instead of the whole class? What is the point of using sealed class?
private: private limits the visiblity to a scope. Declaring a private class within a class means that sub-class can't be seen from outside of the class.
This is also true for methods and properties - they can be seen within the class, but not to any consumers or inheritors.
private keyword is used for declaring class.
sealed: If a class is declared as sealed, that means that you cannot inherit from the class. sealed class can be used when a class is internal to the operation of the library, class or why you do not want that class to be overridden because it may affect the functionality.
sealed keyword is used for declaring class
example
public class Parent {
// some thing at here
private readonly SubClass sc;
// ctor
public Parent () {
sc = new SubClass();
}
public string foo () {
return sc.bar();
}
private class SubClass {
// have some thing here
public string bar() {
//..............
return "...........";
}
}
}
You need to understand difference between inheritability and accessibility.
If you want to make your class non-inheritable, making it sealed is the best option. Also a class can not be protected, private or internal protected. Only sub class can have those access specifiers. A normal class which is directly under a namespace can only be public or internal.
Now coming to you point of making all the members private in the base class. Doing that does not serve any purpose.
You inherit a class only to reuse certain properties and/or method or override them in the inherited class. If you make all the members private in the base class you won't be able access them outside even using the object of base class.
Then what's the point of having them in the base class.
public class MyClass
{
private void MyMethod() //You can not inherit this method but you can not use it using 'MyClass' also.
{
//Some code.
}
}
MyClass myObj = new MyClass();
myObj.MyMethod(); // You can not do this as the method is private.
Now if you inherit this class in another class
public ChildClass : MyClass
{
public void ChildMethod()
{
// Some Logic
}
}
Now when you do
MyClass obj = new ChildClass();
You can not do
obj.MyMethod(); //coz this is private method.
You can not do following too.
obj.ChildMethod(); //coz that method is not known to MyClass.
So if you are making members private just for the sake of making them not available for inheritance, you are losing their accessibility from the base class too.
Understood your confusion,
First of all there is no independent private class inside a namespace, compiler throws an error.
If you make a method void m1() private inside public class A, then the method m1 is not accessible from public class B.
Sealed classes are accessible to other classes though it stops inheritance, meaning you cannot use it to derive from.
In the example below, you wont be able to access the method privatemethod from the Main(), but sealed class and sealed method can be accessed. So sealed can be accessed though cannot be inherited, that's the difference.
namespace ConsoleApp1
{
using System;
public class A
{
public virtual void test()
{
Console.WriteLine("Class A");
}
}
public class C
{
public void testSealFromOutsideClass()
{
B instanceB = new B();
instanceB.test();
}
}
public sealed class B : A
{
public override void test()
{
Console.WriteLine("Class B");
}
private void Privatemethod()
{
Console.WriteLine("Printing from a private method");
}
}
//public class C : B {}
public class TestSealedClass
{
public static void Main()
{
A a = new B();
a.test();
C c = new C();
c.testSealFromOutsideClass();
B b = new B();
Console.Read();
}
}
}

How to get a reference to an instance of a derived class from within a base class

.Net 3.5, using C#
I have an instance of a class (A) that has been called via a virtual method from a derived class (B). Within the method (a method of class A) I have discovered the Type of class B that has made the call, and using reflection I have examined class B and discovered a property whose value I want to access.
Is there any way via reflection to get the instance reference to class B? The only object I have is my ‘this’ reference.
[ Edit ]
By way of explaining that I'm not totally nuts for needing to do this: My class is T4NmpBase (class A). I have no control over the class in which I am inheriting (TextTransformation) or the class that inherits from me (TextTemplating - class B). I would like to use the "Host" property if it exits but do not want to put any burden on the programmer who is writing the text templating code that generates the TextTransformation class.
//
// this is my class
//
public abstract partial class T4NmpBase : Microsoft.VisualStudio.TextTemplating.TextTransformation {
public override void Initialize()
{
//
// determine derived class info and get value of "Host" property if it exists
//
}
}
//
// this class is generated by T4 in a project that I have no control over
//
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "10.0.0.0")]
public partial class PPTest : T4_NMP_Base.T4NmpBase {
public virtual global::Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost Host { ... }
public override void Initialize()
{
base.Initialize();
}
}
In your case (assuming I follow correctly) your this reference is really your class (B) type, so you can use that to get the value of the property. So, just to make sure I follow correctly, you've got something that looks like:
public class ClassA
{
public virtual void VirtualMethod()
{
// Do your property investigation here
}
}
public class ClassB: ClassA
{
public override void VirtualMethod()
{
// Code for ClassB
}
}
And you are invoking the virtual method using something like:
ClassA instance = new ClassB();
instance.VirtualMethod()
So if that is the case then you should be able to get the value of the property by:
PropertyInfo proeprtyOnClassB // Assume you got this already via reflection
object propertyValue = propertyOnClassB.GetGetMethod().Invoke(this,null);
This sounds like a real problem with your design.
Is it possible to take Class B's property in question and make it a virtual property of Class A? Then you can override it in B but still access B's property from A. For example:
class A
{
public virtual string P
{
get { return "A"; }
}
public A()
{
Console.WriteLine(this.P);
}
}
class B : A
{
public override string P
{
get { return "B"; }
}
public B() : base() { }
}
When using:
B b = new B(); // prints "B"
If I understand correctly, from class A you want to access the functionality of the current instance through its concrete type B. Unless the member is not accessible to A because it's non-public, defined in another assembly, etc you don't need reflection. The following will work if the code in class A can see the members of derived class B.
B thisAsB = this as B;
if (thisAsB != null) {
// ...
}
But it does call into question the design of the class because class A should not have to know anything about its subclasses.

Categories

Resources