user623566
user623566

Reputation:

Get Value from Different (Non-Referenced) assembly

I have two Projects (under same solution) - Teacher and Student. Student project has reference of Teacher.

public static class Student
{
public static readonly string SchoolName="ABC University";
}

Now how can I access SchoolName from Teacher project.

Is it really possible? If yes, can you please tell me the way.

I am noob in programming. So, pardon me if this is a very silly question. Thanks in advance.

Upvotes: 2

Views: 123

Answers (3)

jparthj
jparthj

Reputation: 1636

Yes this is possible. You can access the assemblies which you have not referenced to your project. Following is the code you can use.

In the following method, i have a user control in the assembly and i am accessing that without referencing it. You can change the code as per your need. This code is in VB, you need to change it to c#. :-)

        Dim oAssembly As Assembly = Nothing
        Dim oType As Type = Nothing
        Dim oUserControl As System.Windows.Forms.UserControl = Nothing

Dim oArgs As [Object]() = New [Object]() {Me} 'Arguments that you need to pass to the assembly

        Try
            ' Set Assembly 
            oAssembly = Assembly.LoadFrom("Your DLL Path")

            For Each currentType In oAssembly.GetTypes()
                If currentType.Name.ToLower.Contains("Name of the class or object in assembly") Then
                    oType = currentType
                    Exit For
                End If
            Next

            oUserControl = DirectCast(oAssembly.CreateInstance(oType.FullName, True, BindingFlags.CreateInstance, Nothing, oArgs, Nothing, Nothing), System.Windows.Forms.UserControl)

            Return oUserControl
        Catch ex As Exception
            Return Nothing
        End Try

Upvotes: 0

Tintenfiisch
Tintenfiisch

Reputation: 360

You can make a third project. This project is referenced by the two other. In the third project you can save, e.g. global values in an easy way. (such as your static values). But sure, you have to set the values in the third project by your Student project.

To access real "object" properties, you will have to make a little bit more work, like defining general Interfaces in the third project.

But I can think you can go with the first approach.

Maybe not the best way, but a way that works.

Upvotes: 2

Peyton Crow
Peyton Crow

Reputation: 882

Here are some steps:

  1. Add Reference of Student Project to Teacher Project
  2. You can access the static class Student, by coding from Teacher Project like this:

    void DoSomething() {
        string schoolName = Student.SchoolName;
    }
    

Upvotes: -1

Related Questions