0

I want to share code from a C# project inside a VB.Net project. I want to refer a public class and its variables inside VB. So I've put both VB and C# project inside the same solution. Here is the declaration of C# class insde C# project:

public class MyUtils
{

    public static byte[] zeroArray = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    ....

When I want to refer it inside VB I will have below errors: 'MyUtils' is not accessible in this context because it is 'Friend'.

I have change the accessibility of every object to public in C# but I don't know how to allow access to C# class. I should add that I have not enough familiarity with VB and its inheritance mechanisms.

4
  • 1
    Not familiar with VB.net but am aware that c#/vb can share code a quick google showed this Commented May 1, 2021 at 8:33
  • 1
    It is possibly to have a solution with C# and VB projects. I have worked with an example, but cannot access it anymore Commented May 1, 2021 at 9:20
  • 1
    Friend in vb.net is the same as internal in C#. So the snippet you posted does not match the error message at all. The C# assembly you actually used did not yet have public in the class definition. Do make sure that the vb.net and C# projects belong to the same solution and that the vb.net project uses a project reference instead of a file reference to avoid such mishaps. Commented May 1, 2021 at 12:42
  • @HansPassant I don't know why it happened. My C# project was change to a class Library and I referenced it in VB.NET project. But the error was as above. When I changed the VB.NET project to reference dll file of C# project it work without any problems! Commented May 2, 2021 at 5:52

1 Answer 1

1

I created a C# console app named "ConsoleApp2" using .NET Framework 4.8 and added a class named "MyUtils":

namespace ConsoleApp2
{
    public class MyUtils
    {
        public static byte[] zeroArray = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

    }
}

I built the project to make sure that worked.

Then I added a VB.NET console app project named "ConsoleApp1" to the same solution. I added a reference to the ConsoleApp2 project:

Add reference dialog

and used this code:

Module Module1

    Sub Main()
        Dim bb = ConsoleApp2.MyUtils.zeroArray
        Console.WriteLine(String.Join(" ", bb.Select(Function(b) b.ToString("X2"))))
        Console.ReadLine()

    End Sub

End Module

and ran it to get the output:

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.