2

What is the equivalent of Type from VBA in C#?

I am asking, because I have some code in Excel which I am trying to turn into a standalone C# application. I have a function, which comes from a .dll, which takes in a Type with some strings and longs as an argument. How would I replicate this in C#? Will this even work, or the will the function from .dll not even work in C#?

I haven't yet experimented with this, because it is all connected to a working database, and I want to know how this would work before I mess something up.

TK-421
  • 294
  • 1
  • 7
  • 26
  • 1
    What dll? Is it a managed .Net assembly? – Fildor Jul 01 '19 at 09:04
  • 1
    Judging from linked Docs, that would be a class or struct. But I am suspicious if a C# implementation would be compatible with your "dll". But maybe (and probably) there is a decent replacement on nuget ... – Fildor Jul 01 '19 at 09:05
  • 1
    I believe you are looking for [struct](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct). – John Wu Jul 01 '19 at 09:07
  • Thank you, I will try with struct. – TK-421 Jul 01 '19 at 09:07

3 Answers3

2

The example in the linked documentation would be rewritten as:

struct StateData 
{
    int[] CityCode;
    string County;
}

var Washington = new StateData[100];

Although at some point you'd have to initialize CityCode. In VBA you could do it implicitly but in c# you'd have to write something like:

foreach (var w in Washington) w.CityCode = new int[100];
John Wu
  • 50,556
  • 8
  • 44
  • 80
2

You say that you use a Type in VBA to pass data to a function contained in some DLL. Seeing some code would help, but this technique is usually used to call a (Windows API or third-party) DLL expecting some C-type struct.

In C#, you would use P/Invoke to call functions in unmanaged DLLs, and you would typically use a struct for complex types required by the DLL. Using a class is also possible, but there are some subtleties to be aware of.

A simple example can be found in this SO answer:

If your DLL is part of the Windows API, you can use http://pinvoke.net/ to find ready-to-use C# declarations for the functions as well as the data structures.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

The closest will be the Struct datatype. It is similar in that it is a user-defined data type containing one or more elements (members) of various data types, and these elements are accessed as fields of the Type/Struct.
Both are values types and use stack allocation (usually).

AAA
  • 3,520
  • 1
  • 15
  • 31