Saeid Saeid -4 years ago 51
C# Question

why I am getting " 'some class' does not contain a definition for 'some method' " error while the class has that method?

I am trying to finish a simple tutorial for using c++ library with c# console application.
Here I have a simple class library:

cpp file:

#include "stdafx.h"

#include "ClassLibraryCPP.h"

using namespace ClassLibraryCPP;

void myClass::test()
{
Console::WriteLine("hello cpp/cli!");
}


header file:

#pragma once

using namespace System;

namespace ClassLibraryCPP
{

public class myClass
{
public:
void test();
};
}


and now here is my c# console:

using ClassLibraryCPP;

namespace ConsoleApplicationCS
{
class Program
{
static void Main(string[] args)
{
myClass testClass;
testClass = new myClass();
testClass.test();
}
}
}


and I get this:


'myClass' does not contain a definition for 'test' and no extension
method 'test' accepting a first argument of type 'myClass' could be
found (are you missing a using directive or an assembly reference?)


But I have made
myClass
and
test
method
public
so why
.test()
is not visible to console application?




Update:
adding ref to make managed class and then rebuilding the C++ project (by right clicking and rebuild not just rebuilding the solution) solved the problem.
I also found this question related:
C# code can't "see" the methods in my C++ dll
I still don't get how this works:
https://www.youtube.com/watch?v=xTRTY-fOIe8&t=1800s

Answer Source

Make your class managed:

public ref class myClass
{
public:
    void test();
};

Change method declaration:

void ClassLibraryCPP::myClass::test()
{
  Console::WriteLine("hello cpp/cli!");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download