Is it possible to pass a custom object (like MyClass[]) from C# to VBA using COM?
If not, which is the best solution to get this working?
I assume you're talking about Excel VBA to C# ...
here's a minimal C# class that does it, in a project w default name ClassLibrary1:
using System;
using System.Runtime.InteropServices;
namespace Tester
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TestClass
{
public double D { get; set; } // simple property to get, set a double
public string S { get; set; } // simple property to get, set a string
}
}
and here's VBA to try the class out:
Private Sub foo()
Dim X As New ClassLibrary1.TestClass
X.S = "Hello"
Debug.Print X.S ' prints "hello"
X.D = 12
Debug.Print X.D ' prints a 12
End Sub
and here are the extra things you need to do to make this work:
(1) in C# Project...Properties...Build ==> check "Register for COM interop
(2) in C# Project...Properties...Application...Assembly Information ==>
check "Make assembly COM-visible"
(3) in VBA ... Tools ... References, browse to the C# bin output directory and select the "*.tlb" file
Note: this scheme may fail depending on what you add to the class - I don't think VBA will "see" static classes or classes w other than default constructors. You also cannot map VB collections to .NET collections, but you will be able to pass basic types (double, long) and arrays of the basic types back and forth. Also - the "Autodual" option used is a cheap way to get methods exposed ... easy to get started but less efficient and exposes all public methods. Better practice (but more work) would be to set up your own interfaces. If you expand the members of this TestClass to include instances of other classes you have defined, and if you likewise expose those class methods via AutoDual or via hand-coded interfaces, then those classes and their (non-overloaded) methods will likewise be visible in VBA (with Intellisense).
Hope this helps.
I have found several links to methods of making extension methods work in .NET2.0 (The moth, Discord & Rhyme, Stack Overflow). I have also heard vaguely from a colleague that this causes some problems with libraries or something? Is this the case? Also all 3 use different methods:
The moth:
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
}
Discord and Rhyme
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class ExtensionAttribute : Attribute {}
}
Stack Overflow
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
| AttributeTargets.Method)]
public sealed class ExtensionAttribute : Attribute {}
}
Whats the difference between these methods, and which one would you recommend?
Ultimately it isn't going to make much difference; you could argue that the one that matches the runtime is preferred, but the ideal answer is to switch to .NET 3.5 (otherwise at a later date it can get confusing with different versions of the same attribute in scope etc).
The [AttributeUsage] will prevent it being attached to things where it won't do anything - but it won't do aything by itself anyway...
Looking at metadata against the type, the exact attribute usage seems most like the stackoverflow variant - but ultimately this isn't hugely important - the name and namespace is all that matters (and that it inherits from Attribute).
The difference is simple enough:
In your first example, you can put the attribute anywhere. In the second example, you can only apply it to a method, never more than one to the same method and an inherited class with the method overridden will not inherit the attribute. In the third example, you can apply it to a method, a class or an assembly.
If you try to apply it in any other place, you will get a compiler error.
The second seems to make most sense.
I would recommend Discord and Rhyme because it providing meaningful constraints for how the attribute is supposed to be applied.
It can only be applied to methods
You can only apply it once
The attribute cannot be inherited
Personally, I would recommend avoiding all three. Each option makes this work by performing a "trick" - I would not rely on this for production code.
If you want to use extension methods, upgrade to C# 3.0. Otherwise, just stick to calling the method using the non-extension method syntax.
You can always take an extension method call like so:
public static class Utility {
public static string Extension(this string original) { ... }
// call with:
var newString = myString.Extension();
And call it directly:
string newString = Utility.Extension(myString);
This will be more consistent with C#/.NET 2 syntax, and would be my recommendation.
The SO version is the accurate one, for the pure sake of accuracy you should use it.
Fwiw, the AttributeTarget.Method specifier is crystal clear. Class and Assembly less so. Both the C# and the VB.NET compiler emit the attribute on the static class / Module that contains the extension method. And on the assembly that contains the class / Module. Why they do this is less crystal clear, it wouldn't be needed to properly compile them. I'm guessing this is an optimization at work, helping both the compiler and IntelliSense discover when an extension method should be considered.
Getting the attribute applied to the assembly is actually a problem. That won't work right when you compile code to .netmodules. But that's a very obscure issue.
I've seen some guides or blogs that say using this to access a class's own members is bad. However, I've also seen some places where professionals are accessing with this. I tend to prefer explicitly using this, since it seems to make it clear that the thing I'm accessing is part of the class.
this.MyProperty = this.GetSomeValue();
Is there some advantage or disadvantage to using this? Is it simply a stylistic preference?
If it adds to the clarity of the code, use it , if it doesn't don't. There are a few places it does add clarity - for example in C++:
struct Point {
int x, y;
Point & operator=( const Point & p ) {
this->x = p.x;
this->y = p.y;
return *this;
}
};
In cases like this, when you have two objects of the same type to refer to I find that the use of this can clarify things (though note that in C++ the above assignment operator implementation is not necessary).
I always use this. because it makes code more readable in my opinion. It makes instantly clear that
It's a member of this instance.
Clarifies if base class is called (base.) or the overriding member (this.)
It's not a static member.
It's not a call to a member of another static class (this.Monster.Legs.Run(); vs Monster.Legs.Run();).
Having gone from using this for years, to finding not many people (atleast in my experience) use it, I eventually changed. The benefits I can see of having this-less code:
I use underscores: _myVar for private variables, which don't need a this as they're always member variables.
For method calls it is very obvious that it's part of the class. You would prepend the type name if it wasn't.
(C#) Private variables and parameters are always camel case.
If your class is so big it's getting confusing you've got an issue with cohesion and separation of concerns anyway.
(C#) Visual Studio color codes types, so you know if you're using a property or type:
e.g.
someclass.Method(1);
SomeClass.StaticMethod(1);
I can see that if you don't use the underscores naming convention, and have a large method with a weighty body it could lead to some confusion.
Static methods or properties can occasionally confuse things, but very rarely.
You will obviously always need the this keyword when passing references, for example:
someclass.Method(this);
var someclass = new SomeClass(this);
(I write C#, but my answer relates to Java)
It's sometimes necessary, e.g. in a constructor (in C# or Java) if you are assigning a field from a parameter of the same name.
I use this, because it seems more readable to me. And...
StyleCop rule SA1101: PrefixLocalCallsWithThis says:
Cause
A call to an instance member of the local class or a base class is not prefixed with ‘this.’, within a C# code file.
Rule Description
A violation of this rule occurs whenever the code contains a call to an instance member of the local class or a base class which is not prefixed with ‘this.’. An exception to this rule occurs when there is a local override of a base class member, and the code intends to call the base class member directly, bypassing the local override. In this case the call can be prefixed with ‘base.’ rather than ‘this.’.
By default, StyleCop disallows the use of underscores or m_ to mark local class fields, in favor of the ‘this.’ prefix. The advantage of using ‘this.’ is that it applies equally to all element types including methods, properties, etc., and not just fields, making all calls to class members instantly recognizable, regardless of which editor is being used to view the code. Another advantage is that it creates a quick, recognizable differentiation between instance members and static members, which are not be prefixed.
A final advantage of using the ‘this.’ prefix is that typing this. will cause Visual Studio to show the IntelliSense popup, making it quick and easy for the developer to choose the class member to call.
How to Fix Violations
To fix a violation of this rule, insert the ‘this.’ prefix before the call to the class member.
Regarding to C++, when using templates it's sometimes necessary to use this to help compiler with name resolution:
template <typename T>
class Base {
public:
void exit();
};
template <typename T>
class Derived : Base<T> {
public:
void foo() {
exit(); // calls external exit() or error
// so you should use this->exit() if that was your intent
}
};
The general rule should be: use "this" to avoid ambiguity, don't use this if it's obvious to what you refer.
For example, when progamming in Java, this.getSomeValue() is not needed, since all function calls are method calls on "this". On the other hand, this.myProperty might be useful if there are lots of local variables within your method, or if there are static member variables, and you want to make clear that you access an instance variable.
Of course, sometimes "this" is unavoidable, as in
void setX(int x){ this.x = x; }
In objective-c
...
prop = value; // just an assignment
...
and
...
self.prop = value; // !!! equivalent to method call [self setProp:value]
...
differ much - you must be aware of what and why you're doing.
It's frowned upon, almost all of the time in general use. I never use "this" like that.
People do it because they get Intellisense in their editor by typing "this" and then a "dot". You also see it around a lot of places when automatic code generators are doing the coding.
Now as to the question to why using "this" throughout your code is a bad idea. First off, it can be used as a crutch to cover up the lack of a good naming convention. For example, I consider this block of code to be a "coding horror":
class Fudge {
public decimal PoundsOfChocolate {get; set;}
Fudge (decimal PoundsOfChocoloate) {
this.PoundsOfChocolate = PoundsOfChocolate;
}
}
Yuck. Better to use an agreed upon naming convention:
class Fudge {
public decimal PoundsOfChocolate {get; set;}
Fudge (decimal poundsOfChocoloate) {
PoundsOfChocolate = poundsOfChocolate;
}
}
Why is this better? Well, in the trivial case like the above example, it doesn't matter all that much. Things get worse when your functions get longer, and you have private variables in complex functions which might collide with your members.
Also, if you pepper your code with "this" keywords, it becomes more difficult to read since there is more repetitive text. And it is just more verbose without adding semantics. IMO more verbosity without added semantics is bad. My two cents. Downvote all you want.
That isn't to say that "this" has no valid uses. Far from it. If you use it to resolve the difference between calling a base member and a member in the current object, then it has its place. It has its place in code generators as well. But as whiskey has taught me, overuse of anything leads to pain.
I agree with Dave. It is longer.
It is simply a matter of style, there is no other effect.
It's primarily used for constructors and initialization functions (and I prefer this style to various underscores):
MyClass(hisValue) { this->hisValue = hisValue; }
Using this style everywhere is just a syntax bloat reminiscent of Hungarian notation. If you keep functions reasonably short, local variables and function parameters are immediately recognizable to the reader of code. If declaration is not within screen, it can can be assumed then to be a class member - so 'this' notation doesn't add any useful information.
I always use this for a simple reason:
(Example in C# but won't make a difference)
Take for example a class like this:
class Foo {
private int count = 0;
public List<Int32> foos = new List<Int32>();
public int DoCounting() {
foreach (Int32 foo in foos) {
if (foo > 50) ++count;
}
return count;
}
}
Now another coder of your company has to add a function quickly, i.e. count another loop. He doesn't look at your code but simply adds his own due to the time critical request (or because it's 11:59am and he wants to make a break):
class Foo {
private int count = 0;
public List<Int32> foos = new List<Int32>();
public List<Int32> bars = new List<Int32>();
public int DoCounting() {
int count = bars.Count;
for (int i = 0; i < count; ++i) {
bars[i]++;
}
foreach (Int32 foo in foos) {
if (foo > 50) ++count;
}
return count;
}
}
Now what happens? And how easily could this be prevented by always using this?
Ofc the example is unrealistic but it happens easily in more complex classes and methods and causes hard to track bugs.
Using this makes codes more cleaner and readable. Also you have no option but to use in a situation where the parameter name is the same as a member variable. How do you distinguish the two?
class Test {
int a;
void doA(int a) {
this.a = a; //if you do a=a its gonna be a bug really hard to catch
}
}
I would suggest always using this unless the code would behave differently if you did not. It at least acts as syntactic sugar for the programmer/reader to indicate that the RHS is coming from the current class.
Also, in some languages (Perl being one), if you leave off the object reference, then the inheritance heirarchy is not used when resolving the RHS. e.g. if methodName is defined in the parent, then $this->methodName() will work, but methodName() will fail because only the current package is searched.
It is really useful in a constructor where code like
this.field = field;
becomes more readable. I would put in methods too! Coloring of this doesn't hurt either.
I use System.Data.SQLite and C# for accesing SQLite databases/tables. For lazy and fast development reasons, I created my own library of classes to encapsulate some of System.Data.SQLite methods in one method, and to create many common database routines (methods) that let me reduce my work when accessing to data.
If I would inherit System.Data.SQLite library instead of referencing it would help me to optimize my work, ¿is this possible? ¿may you give an example, please?
It's possible to inherit from SQLite and make additions to some of the classes, particularly SQLiteConnection. However, you won't be able to use your own classes everywhere as SQLite will internally create a lot of classes like SQLiteCommand and SQLiteParameter and you don't have an option to tell SQLite to use your custom versions. There is a SQLiteFactory, but this is used for ADO.NET data provider integration and is not used internally by SQLite.
You're much better off keeping your methods separate. If you want them to feel like they're part of the library you can use Extension Methods
This is a great question and I didn't find much in the way of answers 7-years later! I just had to do a simple inherit and found it a little tricky (because I wasn't completely familiar with constraining a generic type). But here's what I ended up with that worked.
using SQLite; // Here using sqlite-net-pcl
using System.Collections.Generic;
namespace SQLiteEx
{
class SQLiteConnection : SQLite.SQLiteConnection
{
// Must provide a constructor with at least 1 argument
public SQLiteConnection(string path)
: base(path)
{
}
// With this class, you can automatically append
// some kind of global filter like LIMIT 1000
string mGlobalFilter = "";
public string GlobalFilter
{
set { mGlobalFilter = value; }
get { return string.IsNullOrWhiteSpace(mGlobalFilter) ? "" : " " + mGlobalFilter; }
}
// You MUST constrain the generic type with "where T : new()"
// OTHERWISE feel the wrath of:
// ===================================================================
// 'T' must be a non-abstract type with a public parameterless
// constructor in order to use it as parameter 'T' in the generic
// type or method 'SQLiteConnection.Query<T>(string, params object[])'
// ===================================================================
public List<T> Query<T>(string sql) where T : new()
{
return base.Query<T>(sql + GlobalFilter);
}
}
}
I have a C# library with the following Namespace/Class:
namespace Helper
{
public static class Util
{
/*static methods*/
}
}
I have referenced said library in a F# project and when I try to call one of the methods I get:
error FS0039: The namespace or module 'Helper' is not defined.
This is an example of the method call not working:
#light
let a = Seq.skip 1000 (Helper.Util.GetPrimes 200000);;
Am I missing something obvious? Using open Helper doesn't work either, and the weird thing is that IntelliSense does work, it lists every method in the Util class.
Also, what is the standard practice for calling functions in some of my files from other files in the same project? I don't wanna create full objects just to access a few functions.
Regarding multiple files, see the first portion of "Using multiple F# source files, and a useful debugging technique", as well as the final portion of "Sneak peeks into the F# project system, part three". The former discusses how top-level code in a file implicitly goes in a module of the same name as the filename, whereas the latter discusses how to order files in the project (since you can only see stuff declared above/before you).
What does your GetPrimes method look like? It work for me...
I have a solution with a C# library including this code:
namespace Scratch
{
public static class Util
{
public static IEnumerable<int> GetNumbers(int upto)
{
int i = 0;
while (i++<upto) yield return i;
}
}
}
And calling it from a F# project that references the C# project like this:
#light
let p = Seq.skip 1000 ( Scratch.Util.GetNumbers 2000000);;