properties of c# class is not visible at visual basic 6.0 - c#

I have created a class in c# and made the com visible property is true. But, i could not see the its properties at visual basic 6.0. what could be a problem? please help me

Define a public interface that is also ComVisible, and have your class implement that.
Then use tlbexp.exe to generate a type libary from your C# assembly:
tlbexp ComServer.dll /out:ComServer.tlb
You need to add a reference to the type library from VB6, not the assembly. How does VB6 know where your assembly actually is then? Regasm is how. It is the equivalent of regsvr32 for .net assemblies.
regasm ComServer.dll

Do you apply ComVisible(true) to class?

As long as you make your class ComVisible in Properties (of Visual Studio 2005 or 2008, or set the ComVisible attribute to True in the Assembly file), you should be able to see your class in VB6. To get intellisense you need to declare an interface, give it a GUID, and implement it as shown in the example code below (Note: you have to create your own unique GUID's for both the interface and the concrete class.
using System.Runtime.InteropServices;
using System.Drawing;
namespace example_namespace
{
[Guid("1F436D05-1111-3340-8050-E70166C7FC86")]
public interface Circle_interface
{
[DispId(1)]
int Radius
{
get;
set;
}
[DispId(2)]
int X
{
get;
set;
}
[DispId(3)]
int Y
{
get;
set;
}
}
[Guid("4EDA5D35-1111-4cd8-9EE8-C543163D4F75"),
ProgId("example_namespace.Circle_interface"),
ClassInterface(ClassInterfaceType.None)]
public class Circle : Circle_interface
{
private int _radius;
private Point _position;
private bool _autoRedeye;
public int Radius
{
get { return _radius; }
set { _radius = value; }
}
public int X
{
get { return _position.X; }
set { _position.X = value; }
}
public int Y
{
get { return _position.Y; }
set { _position.Y = value; }
}
}
}

Related

Using class to describe data in C#

I'm writing an application in C#, which supports plugins. Each plugin has to introduce itself, such that application can prepare appropriate environment for it. The current info object looks more less like this:
class FilterInfo
{
public InputInfo[] inputs;
public OutputInfo[] outputs;
bool IsConfigurable;
bool IsPlayable;
string TypeName;
}
This structure will surely expand in future (however, I guess, that not much, it'll maybe double its size). I'm currently thinking on how to implement such info class properly.
In C++ I would do it the following way (I'll strip the class to one field to make the examples more readable):
class FilterInfo
{
private:
std::vector<const InputInfo> inputs;
public:
std::vector<const InputInfo> & GetInputs()
{
return inputs;
}
const std::vector<const InputInfo> & GetInputs() const
{
return inputs;
}
}
Now, the plugin would instantiate a FilterInfo class, fill-in its fields and then return const FilterInfo on request, such that noone may change contents of the info (well, noone should).
In C#, I can only imagine the following "safe" solution:
public interface IInputInfo
{
bool SomeData
{
get;
}
}
public class InputInfo : IInputInfo
{
private bool someData;
public bool SomeData
{
get
{
return someData;
}
set
{
someData = value;
}
}
public bool IInputInfo.SomeData
{
get
{
return someData;
}
}
}
public interface IFilterInfo
{
ReadOnlyCollection<IInputInfo> Inputs
{
get;
}
}
public class FilterInfo : IFilterInfo
{
private InputInfo[] inputs;
public InputInfo[] Inputs
{
get
{
return inputs;
}
set
{
inputs = value;
}
}
public ReadOnlyCollection<IInputInfo> IFilterInfo.Inputs
{
return inputs;
}
}
The plugin will, of course, return IFilterInfo instead of FilterInfo, such that the data is readonly (OK, I know about reflection, the matter is to notify the user, that the data should not be changed). However, this solution looks very clumsy to me - especially when compared to compact version I cited earlier.
Another solution may to be create FilterInfo only with getters, but it would require passing the data into it in some way and probably would end up with a huge constructor with lots of parameters.
Edit: Another solution is to create a struct and return its copy during every request. However, arrays are copied by reference, so I would have to copy them manually each time.
Yet another one is to construct the FilterInfo from the scratch each time anyone requests it, eg.
public FilterInfo Info
{
get
{
return new FilterInfo()
{
IsConfigurable = true,
IsPlayable = false,
Inputs = new[]
{
new InputInfo()
{
// (...)
}
}
}
}
}
Is there an elegant way to solve this problem?
I think you got it almost right the first time:
Define a public IFilterInfo interface in the pluggable assembly that only allows reading.
Implement the interface in a FilterInfo class in the plugin assembly that has internal setters on its properties.
Have a method return a new instance of the FilterInfo class upon request. Convention suggests to use a method instead of a property in cases where a new instance is constructed each time. (If you insist on using a property you could store the instance once it has been constructed and return it through the property)
Example:
In the pluggable assembly:
public interface IFilterInfo {
bool IsPlayable { get; }
bool IsConfigurable { get; }
}
In the plugin assembly:
internal class FilterInfo : IFilterInfo {
public bool IsPlayable { get; internal set; }
public bool IsConfigurable { get; internal set; }
}
public IFilterInfo GetFilterInfo() {
return new FilterInfo() { IsPlayable = true, IsConfigurable = false };
}
Internal setters and a read-only interface should be enough to ensure that the properties aren't modified outside the plugin assembly.
What about setting the setters to private or protected.
public class FilterInfo
{
public InputInfo[] inputs { get; private set; }
public OutputInfo[] outputs { get; private set; };
bool IsConfigurable;
bool IsPlayable;
string TypeName;
public void SetInputs(...)
{
InputInfo[] allInputs;
//do stuff
inputs = AllInput;
}
public void SetOutputs(...)
{
OutputInfo[] allOutputs;
//do stuff
outputs = AllOutput;
}
}
You would be able to have internal methods to set the data or go protected and allow modifying the objects through inheritance.
UPDATE
What about using the internal accessor for the setter. This way nothing will be able to access the setter unless it is declared in the InternalsVisibleTo assembly level attribute, which would be defined in the assembly containing FilterInfo.
The following post gives a good explanation on how to do this using the internal keyword.
Internal Description
UPDATE
Another solution may to be create FilterInfo only with getters, but it would require passing the data into it in some way and probably would end up with a huge constructor with lots of parameters.
According to this the only issue with not having a getter is that you still need to pass in data. The original solution allows this to happen. I guess I might be a little confused. If the plugin is able to change the information in this API which is by reference I am guessing. Then if the application is referencing the same assembly, it too would have the same accessors provided to the plugin. It seems that short of setting the setters to internal and allowing access through attributes would be the only way to achieve that type of functionality. But that wont work in your case because you do not know the assemblies that are referencing your API.
I don't quite sure about what you really want, but it seems the builder pattern is good for this case.
First, the setter or constructor can be marked internal, means that only the assembly can access the constructor or setter. Leave the getter public, it is needed, isn't it?
Then your builder class (assume you are using the constructor injection):
public class FilterInfoBuilder{
public FilterInfoBuilder(InputInfo[] inputInfo){
this.inputInfo = inputInfo;
}
private InputInfo[] inputInfo;
public FilterInfo Create(){
FilterInfo filterInfo = new FilterInfo(inputInfo);
return filterInfo;
}
}
Maybe I misunderstand your requirement though.
EDIT
You can tweak the builder as a dynamic setter though. Now consider using internal setter instead of internal constructor.
public class FilterInfoBuilder{
public FilterInfoBuilder(InputInfo[] inputInfo){
filterInfo = new FilterInfo();
filterInfo.InputInfo = inputInfo;
}
private FilterInfo filterInfo;
public FilterInfo FilterInfo{
get{
return filterInfo;
}
}
public void ChangeInputInfo(InputInfo[] inputInfo){
filterInfo.InputInfo = inputInfo;
}
}
You can use FilterInfoBuilder.FilterInfo to access the FilterInfo class. To modify it, you can create internal methods inside the builder class.
I don't really sure about the solution though, as I haven't found the design in any documented source.
More EDIT
I have another design, only if you can separate the interface between assemblies and make sure the application access the interface and not the class.
example:
public interface IInputInfoSetable{
public InputInfo[] InputInfo{
set;
}
}
public interface IFilterInfo{
public InputInfo[] InputInfo{
get;
}
}
public class FilterInfo: IFilterInfo, IInputInfoSetable{
// implement explicitly both of the interface.
}

how to use interface when a class that implements it have its own attributes?

I am using an interface reference variable to access the properties on an Interface
But in addition to that the class that implements the interface has its own attributes.
I am unable to access the class attributes through this interface reference.
Here are my questions:
1) why is that so?
2) What is the solution to the problem? Is there any way i can access the coolant power variable in AC class through machine only? Will a TYPE CAST work?
interface IMachines
{
#region properties
int machineID { get; set; }
static int totalID { get; set; }
string name { get; set; }
string make { get; set; }
int weight { get; set; }
int cost { get; set; }
int warranty { get; set; }
DateTime creationDate { get; set; }
#endregion
int generateWarrantyExpiry();
int searchMachine();
}
public class AC:IMachines
{
#region ACMembers
protected int _machineID;
protected string _name;
protected int _weight;
protected string _make;
protected DateTime _creationDate;
protected int _warranty;
protected int _cost;
public int _coolentPower;
public int CoolentPower
{
get { return _coolentPower; }
set { _coolentPower = value; }
}
#endregion
#region IMachines Members
public int machineID
{
get { return _machineID; }
set { _machineID = value; }
}
public string name
{
get { return _name; }
set { _name = value; }
}
public string make
{
get { return _make; }
set { _make = value; }
}
public int weight
{
get { return _weight; }
set { _weight = value; }
}
public int cost
{
get { return _cost; }
set { _cost = value; }
}
public int warranty
{
get { return _warranty; }
set { _warranty = value; }
}
public DateTime creationDate
{
get { return _creationDate; }
set { _creationDate = value; }
}
public int searchMachine()
{
//Search machine logic to be implemented
return 2
}
public void GenerateWarranty()
{
//generate warranty logic to be implemented
}
#endregion
}
}
Note that using a cast, as many answerers have suggested, will break the abstraction offered by the IMachines interface.
If it's true that you'll only ever be using the one type that implements the interface, AC, then this will work, but if you ever want to support some other type of IMachines, things may break down.
Yes, you can use the "as" keyword to try a cast to the AC class:
IMachines machines = new AC();
(machines as AC).CoolentPower = 3;
One of the fun things about using Interfaces this way is the ability to check if a generic variable implements the interface. For example, you have a generic function that gets run at a lower level. If the object you get given implements IMachines, do something special, or additional, to it.
public void DOSTUFF (object myobject)
{
IMachines machine = myobject as IMachines;
if (machine != null)
{
//do something special for IMachine objects
}
//the rest of the function that gets run against everything
}
and yes, to access the parts of the class that are not defined in the interface you have to cast to the type directly rather than using the interface.
Why is that?
An interface is a declaration of a contract. You are saying that the implementing type conforms to that contract.
When using the interface to access properties, you can only access those properties that the interface declared - how would the interface "know" about these properties? It would need to "know" about all the types that implement it and which one you mean exactly.
The solution is to use the interface when you need the interface abstractions and to use the concrete type when you need to use the type and all its defined properties.
There is a solution, which calls CAST.
So cast to the type of the class implements it to access the properties/methods that not present in the inetrface itself.
var machine = (AC)interfaceVar;
machine.CoolentPower
Or, simply use dynamic
dynamic machine = interfaceVar; //no cast needed ! non need to "know" actual type
machine.CoolentPower
you can access the attributes of your class if you cast it.
var cool = machine as AC;
In answer to 1 - because an interface defines a contract that a class will implement, as such you can change the implementation as long as the contract (ie. the interface) stays the same. What you are trying to do is get to properties that are not part of the contract - what would you expect to happen if you could access the properties of your AC class, but someone passed in an instance of MachineX that implements IMachine but doesn't have the properties of your AC class? The compiler cannot guess what to do in such an instance, hence you have to explicitly tell it that if your machine is an AC, then do something with it as an AC (and that's what the other answers about casting it do).

MATLAB/.NET Interop -Setting property on a .NET object is not allowed

I am writing a DLL in C# which is intended to be used from MATLAB R2011a using the native .NET interop. I have run into a situation where I am not able to set the value of one of the properties on my object. Here is a simple example:
namespace MatlabTest
{
public class Container
{
public int Value { get; set; }
}
public class MatlabDll
{
public MatlabDll()
{
this.Prop = new Container();
}
public Container Prop { get; private set; }
}
public class MatlabDllChild : MatlabDll
{
}
}
Now, I can access the property on objects of type MatlabDll from MATLAB just fine:
NET.addAssembly('MatlabTest.dll');
myObj = MatlabTest.MatlabDll();
myObj.Prop.Value = 5;
However trying to set the same property on an object of type MatlabDllChild fails using
myChild = MatlabTest.MatlabDllChild();
myChild.Prop.Value = 5;
Error message:
Setting the 'Prop' property of the 'MatlabTest.MatlabDllChild' class is not allowed.
Why does MATLAB allow me to set the property on the base class but not the derived type?
Because it has a private setter and those aren't available to Derived Types.
For Example:
public class Base
{
private string baseString = "";
public string BaseString { get { return baseString; } }
}
public class Child : Base
{
}
There is no way to access the set, which is effectively what you have done.
If you need the set to available to derived types use Protected instead.
public Container Prop { get; protected set; }
I tested your example, and although I couldn't assign the property directly, using another (reference) object worked just fine:
myChild = MatlabTest.MatlabDllChild();
tmpObj = myChild.Prop;
tmpObj.Value = 5;
disp( myChild.Prop.Value )
Perhaps this is a bug/limitation in the MATLAB .NET Interface...

C# splitting property get and set between classes. Why doesn't it work?

I'm trying to provide two classes to my users - one that is read-only and one that is writable. The r/o will only have getters, while the writable will inherit from it and add the setters.
I was under the impression that C# should be able to handle it, but the compiler disagreed.
Why doesn't this work? Any workarounds?
class A
{
protected int m_val;
public int Val
{
get { return m_val; }
}
}
class B : A
{
public int Val
{
set { m_val = value; }
}
}
class Test
{
static void Main(string[] args)
{
B b = new B();
b.Val++; // <-- WHY DOESN'T THIS WORK?!
}
}
P.S. the protected variable in the example above is artificial. My class actually wraps some native resources and the getting/setting happens on either const or mutable native pointer.
partial applies to a single type - not 2 types (A and B). You would need something more like below, ideally keeping the field private:
class A
{
private int m_val;
public int Val
{
get { return m_val; }
protected set { m_val = value; }
}
}
class B : A
{
public new int Val
{
get { return base.Val;}
set { base.Val = value; }
}
}
I'm not sure about why you need this, but a possibly better design would be to have two interfaces rather than two classes, and a single class that implements both. Then you could hand your client code whichever interface you'd like them to use, with the added bonus of being able to use the values set on a writable interface and hand it over to someone else as a read-only interface.
Mark the setters as protected in the parent, and expose public setters in the child.

Hiding inherited members

I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer.
These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight.
It's not as much a functional issue as a usability issue. What should I do?
Update
Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator. (I know, it's ridiculous)
Override them like Michael Suggests above and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:
[Obsolete("These are not supported in this class.", true)]
public override void dontcallmeanymore()
{
}
If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated.
While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the EditorBrowsableAttribute:
Using System.ComponentModel;
[EditorBrowsable(EditorBrowsableState.Never)]
private string MyHiddenString = "Muahahahahahahahaha";
Edit: Just saw this in the documentation comments, which makes it kinda useless for this purpose:
There is a prominent note that states that this attribute "does not suppress members from a class in the same assembly". That is true but not complete. Actually, the attribute does not suppress members from a class in the same solution.
One potential thing you can do is contain the object rather than extend from the other class. This will give you the most flexibility in terms of exposing what you want to expose, but if you absolutely need the object to be of that type it is not the ideal solution (however you could expose the object from a getter).
Thus:
public class MyClass : BaseClass
{
// Your stuff here
}
Becomes:
public class MyClass
{
private BaseClass baseClass;
public void ExposeThisMethod()
{
baseClass.ExposeThisMethod();
}
}
Or:
public class MyClass
{
private BaseClass baseClass;
public BaseClass BaseClass
{
get
{
return baseClass;
}
}
}
I think you're best least hackish way is to consider composition as opposed to inheritance.
Or, you could create an interface that has the members you want, have your derived class implement that interface, and program against the interface.
I know there's been several answers to this, and it's quite old now, but the simplest method to do this is just declare them as new private.
Consider an example I am currently working on, where I have an API that makes available every method in a 3rd party DLL. I have to take their methods, but I want to use a .Net property, instead of a "getThisValue" and "setThisValue" method. So, I build a second class, inherit the first, make a property that uses the get and set methods, and then override the original get and set methods as private. They're still available to anyone wanting to build something different on them, but if they just want to use the engine I'm building, then they'll be able to use properties instead of methods.
Using the double class method gets rid of any restrictions on being unable to use the new declaration to hide the members. You simply can't use override if the members are marked as virtual.
public class APIClass
{
private static const string DllName = "external.dll";
[DllImport(DllName)]
public extern unsafe uint external_setSomething(int x, uint y);
[DllImport(DllName)]
public extern unsafe uint external_getSomething(int x, uint* y);
public enum valueEnum
{
On = 0x01000000;
Off = 0x00000000;
OnWithOptions = 0x01010000;
OffWithOptions = 0x00010000;
}
}
public class APIUsageClass : APIClass
{
public int Identifier;
private APIClass m_internalInstance = new APIClass();
public valueEnum Something
{
get
{
unsafe
{
valueEnum y;
fixed (valueEnum* yPtr = &y)
{
m_internalInstance.external_getSomething(Identifier, yPtr);
}
return y;
}
}
set
{
m_internalInstance.external_setSomething(Identifier, value);
}
}
new private uint external_setSomething(int x, float y) { return 0; }
new private unsafe uint external_getSomething(int x, float* y) { return 0; }
}
Now valueEnum is available to both classes, but only the property is visible in the APIUsageClass class. The APIClass class is still available for people who want to extend the original API or use it in a different way, and the APIUsageClass is available for those who want something more simple.
Ultimately, what I'll be doing is making the APIClass internal, and only expose my inherited class.
To fully hide and mark not to use, including intellisense which I believe is what most readers expect
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
I tested all of the proposed solutions and they do not really hide new members.
But this one DOES:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new string MyHiddenProperty
{
get { return _myHiddenProperty; }
}
But in code-behide it's still accessible, so add as well Obsolete Attribute
[Obsolete("This property is not supported in this class", true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new string MyHiddenProperty
{
get { return _myHiddenProperty; }
}
While clearly stated above that it is not possible in C# to change the access modifiers on inherited methods and properties, I overcame this issue through a sort of "fake inheritance" using implicit casting.
Example:
public class A
{
int var1;
int var2;
public A(int var1, int var2)
{
this.var1 = var1;
this.var2 = var2;
}
public void Method1(int i)
{
var1 = i;
}
public int Method2()
{
return var1+var2;
}
}
Now lets say you want a class B to inherit from class A, but want to change some accessibility or even change Method1 entirely
public class B
{
private A parent;
public B(int var1, int var2)
{
parent = new A(var1, var2);
}
int var1
{
get {return this.parent.var1;}
}
int var2
{
get {return this.parent.var2;}
set {this.parent.var2 = value;}
}
public Method1(int i)
{
this.parent.Method1(i*i);
}
private Method2()
{
this.parent.Method2();
}
public static implicit operator A(B b)
{
return b.parent;
}
}
By including the implicit cast at the end, it allows us to treat B objects as As when we need to. It can also be useful to define an implicit cast from A->B.
The biggest flaw to this approach is that you need to re-write every method/property that you intend to "inherit".
There's probably even more flaws to this approach, but I like to use it as a sort of "fake inheritance".
Note:
While this allows for changing the accessibility of public properties, it doesn't solve the issue of making protected properties public.
You can use an interface
public static void Main()
{
NoRemoveList<string> testList = ListFactory<string>.NewList();
testList.Add(" this is ok ");
// not ok
//testList.RemoveAt(0);
}
public interface NoRemoveList<T>
{
T this[int index] { get; }
int Count { get; }
void Add(T item);
}
public class ListFactory<T>
{
private class HiddenList: List<T>, NoRemoveList<T>
{
// no access outside
}
public static NoRemoveList<T> NewList()
{
return new HiddenList();
}
}

Categories