BaseColumns does not contain a constructor that takes 0 arguments - c#

I'm porting an Android Studio project to Visual Studio / Xamarin.
I have this Java code:
public class EmployeeDataContract {
public EmployeeDataContract() { }
public static abstract class EmployeeDataEntry implements BaseColumns {
public static final String TABLE_NAME = "tblEmployeeData"; // Local SQLLite table
public static final String COLUMN_NAME_LOCAL_ID = "_id";
translated to C#:
public class EmployeeDataContract {
public EmployeeDataContract() {}
public abstract class EmployeeDataEntry : BaseColumns { // had to remove "static"
public const string TABLE_NAME = "tblEmployeeData"; // Local SQLLite table
public const string COLUMN_NAME_LOG_ID = "_id";
Visual Studio gives the compile error:
BaseColumns does not contain a constructor that takes 0 arguments
So then I go look at the BaseColumns and it doesn't contain a constructor, nor does it inherit a class (that might have a constructor), therefore it inherits from Object, which should have a constructor with 0 arguments.
What is the problem?

There is a bug report about this behavior here: https://bugzilla.xamarin.com/show_bug.cgi?id=36791
Basically in Java this interface contains just two constants, defining names of id and count columns. In C# interfaces cannot contain constants, so such constants are moved to an abstract class like you see. It cannot be inherited (in other assemblies), because it's only constructor is internal, and child class should call parent's constructor. Because this interface contains only constants, xamarin does not generate (empty) interface for it.
If you are porting code manually (not binding to a Java library) - maybe you can ignore inheriting from this class, since it does not provide anything useful anyway. Of course some another code might only accept instances of this class, but that is unlikely.

Related

C# constructor question, received parent class

There is a bit of C# syntax that I don't understand.
I am on the receiving end of a couple of classes. Simplified, let's say it's this
public class ParentClass
{
public ParentClass();
public RandomEnumerated Random_Enumerated; //No get/set. Relevant?
}
public class ReceivedClass : ParentClass
{
public ReceivedClass();
public char Random_Field { get; set; }
}
When I do this
public class ExtendedReceivedClass : ReceivedClass
{
public ExtendedReceivedClass();
public char A_New_Random_Field_of_My_Own { get; set; }
}
I get hit by the error
ExtendedReceivedClass.ExtendedReceivedClass() must declare a body because it is not marked abstract, extern, or partial FuelTaCSClient
So instead of being able to do what the parental classes do
public ParentClass();
or
public ReceivedClass();
I have to do this
public LocalWreckerVehicleClass() {}
So my question is
a
Is the "public ReceivedClass();" in ReceivedClass the constructor? Same for ParentClass.
b
If it is, why can they do a shortcut version but I can't
or
if it isn't, what is it?
"I am on the receiving end of a couple of classes" -- I think you're looking at those classes using Visual Studio's "Go To Definition" or similar, and they're defined in another DLL?
You'll notice that Visual Studio is showing you method signatures, but not the bodies of the methods: when all it has is a DLL, it's easy to get the signatures, but harder to get the original C# code which was used to build the DLL. This is just intended to give you an overview of what methods are available, and it's not supposed to be valid C#.
public ParentClass(); is not valid C#. It's the signature of a constructor (showing that there's a public parameterless constructor), but when you define a constructor in C# you need to provide a body:
public ParentClass()
{
// ...
}
I am going to accept this as the answer because it seems to make the most sense. I have no trouble believing that when I ask VS to tell me what is in a parent class that it will give me an abbreviated and slightly askew version of what's actually in it.
I am doing a hard search for the parent class by name using a third-party search tool and if I see anything that either affirms or refutes this conclusion I will post an update.
Thank you to everyone who helped! And canton7 - thank you and have this upvote!

Inconsistent accessibility: parameter type 'type' is less accessible than method 'method' in an Interface [duplicate]

I'm trying to pass an object (a reference to the currently logged on user, basically) between two forms. At the moment, I have something along these lines in the login form:
private ACTInterface oActInterface;
public void button1_Click(object sender, EventArgs e)
{
oActInterface = new ACTInterface(#"\\actserver\Database\Premier.pad",this.textUser.Text,this.textPass.Text);
if (oActInterface.checkLoggedIn())
{
//user has authed against ACT, so we can carry on
clients oClientForm = new clients(oActInterface);
this.Hide();
oClientForm.Show();
}
else...
on the next form (clients), I have:
public partial class clients : Form
{
private ACTInterface oActInt {get; set;}
public clients(ACTInterface _oActInt)
...which results in me getting:
Error 1 Inconsistent accessibility:
parameter type 'support.ACTInterface' is less accessible than method
'support.clients.clients(support.ACTInterface)'
c:\work\net\backup\support\support\clients.cs 20 16 support
I don't really understand what the problem is - both fields are private, and accessed by the relevant public method from the form. Googling doesn't really help, as it just points towards one element being public and the other private, which isn't the case here.
Anybody help?
Constructor of public class clients is public but it has a parameter of type ACTInterface that is private (it is nested in a class?). You can't do that. You need to make ACTInterface at least as accessible as clients.
Make the class public.
class NewClass
{
}
is the same as:
internal class NewClass
{
}
so the class has to be public
If sounds like the type ACTInterface is not public, but is using the default accessibility of either internal (if it is top-level) or private (if it is nested in another type).
Giving the type the public modifier would fix it.
Another approach is to make both the type and the method internal, if that is your intent.
The issue is not the accessibility of the field (oActInterface), but rather of the type ACTInterface itself.
What is the accessibility of the type support.ACTInterface. The error suggests it is not public.
You cannot expose a public method signature where some of the parameter types of the signature are not public. It wouldn't be possible to call the method from outside since the caller couldn't construct the parameters required.
If you make support.ACTInterface public that will remove this error. Alternatively reduce the accessibility of the form method if possible.
parameter type 'support.ACTInterface' is less accessible than method
'support.clients.clients(support.ACTInterface)'
The error says 'support.ACTInterface' is less accessible because you have made the interface as private, at least make it internal or make it public.
The problem doesn't seem to be with the variable but rather with the declaration of ACTInterface. Is ACTInterface declared as internal by any chance?
When I received this error, I had a "helper" class that I did not declare as public that caused this issue inside of the class that used the "helper" class. Making the "helper" class public solved this error, as in:
public ServiceClass
{
public ServiceClass(HelperClass _helper)
{ }
}
public class HelperClass {} // Note the public HelperClass that solved my issue.
This may help someone else who encounters this.
You can get Parameter (class that have less accessibility) as object then convert it to your class by as keyword.
In my case I hadone class in a file and I was passing a instance of that class to the constructor of my form in another file.
The problem was had declared the class without the public modifier : class MyClass {}
I could have solved it by changing it to public class MyClass {}
If this error occurs when you want to use a classvariable in a new form, you should put the class definition in the
Formname.Designer.cs
instead of the Formname.cs file.
After updating my entity framework model, I found this error infecting several files in my solution. I simply right clicked on my .edmx file and my TT file and click "Run Custom Tool" and that had me right again after a restart of Visual Studio 2012.
All the answers that say make the type ActInterface as public are right. I am only putting this post to explicitly mention why that's an issue
If a parameter to your public class constructor is private or internal qualified class, it means you wont be able to create an object of that parameter class from outside of the assembly and when you cannot instantiate the parameter object, how can you call this constructor to instantiate an object of this class ?
Try making your constructor private like this:
private Foo newClass = new Foo();

c# Can I prevent my constructor arguments clashing with VBA instantiation?

I'm a bit confused about how I can override constructors requiring arguments when using their classes in a VBA environment.
What works?
I've created several classes in a library, each with an interface to allow full intellisense compatibility when using this library in VBA
With or without constructors, these classes work fine for me e.g.
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("JamHeadArt.ClassEX")]
[Guid("XYZ")]
public partial class ClassEX : IClassEX
{
public ClassEX()
{
// Empty constructor here, some of mine have processes, all work well
}
// Methods/ Properties as outlined by the interface below
}
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("ABC")]
public interface IClassEx
{
// Various methods / fields / properties to be implemented by ClassEX
}
I then add reference to my library and write simple lines of code in VBA to instantiate and access my classes:
Sub Test()
Dim t As JamHeadArt.ClassEX
Set t = New JamHeadArt.ClassEX
' Using t.dot then provides all the methods needed '
End Sub
What goes wrong?
When I create contstructors with arguments (even if optional) in a class, VBA will stop allowing me to create instances of these classes, it tells me the "New" keyword is Invalid and actually won't allow me to choose the class from the intellisense list of objects in my library if I go straight for Dim t As New JamHeadArt.ClassEx even if the parameters are set to optional (therefore not really needed)
The annoying thing here is - I don't actually want my VBA instances to accept parameters via the constructor, they're mainly there for Unit testing and they're optional strings so default to "" ... so I guess my question is something like
Is it possible to override any constructor parameters so when referenced in a VBA environment it will ignore them?
e.g. I really want my constructor to look like this:
public ClassEX(string s = "")
{
}
and in VBA it should work as before Dim t As New JamHeadArt.ClassEX - but it won't with that optional string in there!
You can add an additional constructor, for example:
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("JamHeadArt.ClassEX")]
[Guid("XYZ")]
public partial class ClassEX : IClassEX
{
public ClassEX()
{
// Empty constructor here, some of mine have processes, all work well
}
public ClassEX(string foo)
{
// additional constructor, can be used for unit testing etc.
}
// Methods/ Properties as outlined by the interface below
}

Why does ManyConsole display public members of a CommandLine class?

I'm using ManyConsole as a command line command and options parser for a console app. All commands are defined as a command class that derives from ConsoleCommand, and then implement a specific task. I defined an intermediary base class, ParkPayConsoleCommand derived from that class:
abstract class ParkPayConsoleCommand: ConsoleCommand
{
protected readonly ParkPayDbContext DbContext = new ParkPayDbContext();
}
Then all my command classes derive from my base class, and enjoy a built in DbContext, e.g:
class ReadStartsCommand : ParkPayConsoleCommand
{
public ReadStartsCommand()
{
_commandTrace = new TraceSource(CommandName, SourceLevels.All);
IsCommand("read-starts", "Processes imported vehicle entry movements to create new VehiclePresence records with start date-times based on those movements");
HasRequiredOption("b|batchId:", "The Id of the VehicleMovementBatch used to create new vehicle presences.", b => _batchIdOption = b);
}
public override int Run(string[] remainingArguments)
{
// Do the business of the command.
return (int)ExitCodes.Success;
}
}
It's a ManyConsole convention for each command class to name and describe itself, and define its command line options in its constructor, as you see above. Normally when I run a command such as the ReadStartsCommand above, it just writes to console what command is running, and not what options I passed.
Yet when I make ParkPayConsoleCommand.DbContext public, not protected, it outputs the string
DbContext : ParkPay.Model.Context.ParkPayDbContext
to the console at the end of the running command's name and description. Why does it do this when DbContext is not anywhere defined as a command option itself. This may seem trivial, but essentially I'm asking quite an important 'meta-question', and that is: Does ManyConsole implicitly interpret all public properties of its command classes as command options, even if they are not explicitly declared as such?
I can't speak to the original intent, but as you've found out, yes, it appears to do that. A suggestion of why this might be useful:
Sometimes the commandline options do not map 1-to-1 on to Properties of your ConsoleCommand class. Consider
public class VerbosityCommand : ConsoleCommand
{
public int VerbosityLevel {get;set;}
public VerbosityCommand(){
this.IsCommand("Verbosity","Control the level of verbosity");
this.HasOption("v|verbose","Increase verbosity, cumulative",x => Verbosity++);
}
}
Now the block printed by ManyConsole will (helpfully) have VerbosityLevel : 3 (for example) rather than (unhelpfully) have
Verbose : set
Verbose : set
Verbose : set
or something similar.
Another example would be preset-type flags, which configure a number of properties in to common configurations.
In your case, it might be useful to make _batchIdOption public and ParkPayDbContext protected or private.
Basically yes all public properties are printed as Greg said. This does not imply they are all treated as arguments (and they are not). Some additional points:
if you do any work overriding OverrideAfterHandlingArgumentsBeforeRun() and assign the result to public members, that result will show up when the command is printed to the console. This can be useful to document some intermediate result for the user
to format how the members are printed, you can override ToString on the public member's type
I hope using ManyConsole is smooth otherwise.

Why can't I inherit static classes?

I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.
But it seems I can't declare inheritance for static classes.
Something like that:
public static class Base
{
}
public static class Inherited : Base
{
}
will not work.
Why have the designers of the language closed that possibility?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).
So this:
static class Foo { }
compiles to this IL:
.class private abstract auto ansi sealed beforefieldinit Foo
extends [mscorlib]System.Object
{
}
Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.
Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.
Perhaps you want to add methods to an existing static type. You can do that already via extension methods.
Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.
So, in the end you don't really gain anything from inheriting static classes.
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:
public class TestClass<T>
{
protected TestClass()
{ }
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public class TestClass : TestClass<double>
{
// Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
protected TestClass()
{ }
}
TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)
// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
Unfortunately because of the "by-design" language limitation we can't do:
public static class TestClass<T>
{
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public static class TestClass : TestClass<double>
{
}
You can do something that will look like static inheritance.
Here is the trick:
public abstract class StaticBase<TSuccessor>
where TSuccessor : StaticBase<TSuccessor>, new()
{
protected static readonly TSuccessor Instance = new TSuccessor();
}
Then you can do this:
public class Base : StaticBase<Base>
{
public Base()
{
}
public void MethodA()
{
}
}
public class Inherited : Base
{
private Inherited()
{
}
public new static void MethodA()
{
Instance.MethodA();
}
}
The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.
There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.
P.S.
We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.
My answer: poor design choice. ;-)
This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.
A pseudo example, assuming static inheritance was defined in some way.
public static class MyStaticBase
{
SomeType AttributeBase;
}
public static class MyStaticChild : MyStaticBase
{
SomeType AttributeChild;
}
would lead to:
// ...
DoSomethingTo(MyStaticBase.AttributeBase);
// ...
which could (would?) impact the same storage as
// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...
Very confusing!
But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.
I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:
public static class MyStaticBase<T>
{
public static T Payload;
public static void Load(StorageSpecs);
public static void Save(StorageSpecs);
public static SomeType AttributeBase
public static SomeType MethodBase(){/*...*/};
}
Then you get:
public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
public static SomeType AttributeChild;
public static SomeType SomeChildMethod(){/*...*/};
// No need to create the PlayLoad, Load(), and Save().
// You, 'should' be prevented from creating them, more on this in a sec...
}
Usage looks like:
// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...
The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.
Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.
I believe the right design choice would be to allow static inheritance with specific limitations:
No override of anything. The child cannot replace the base
attributes, fields, or methods,... Overloading should be ok, as
long as there is a difference in signature allowing the compiler to
sort out child vs base.
Only allow generic static bases, you cannot inherit from a
non-generic static base.
You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.
I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
Following are the main features of a static class:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).
When we create a static class that contains only the static members and a private constructor.The only reason is that the static constructor prevent the class from being instantiated for that we can not inherit a static class .The only way to access the member of the static class by using the class name itself.Try to inherit a static class is not a good idea.
I run into the problem when trying to code an IComparer<T> implementation against a third-party library where T is an enum embedded in a class as in the following:
public class TheClass
{
public enum EnumOfInterest
{
}
}
But because the enum is defined within a third-party library class, I can't write the comparer because the following gives a "cannot extends list" error:
public class MyComparer : IComparer<TheClass.EnumOfInterest>
{
}
I'm not even extending a static class -- I'm just implementing a comparer of a enum defined in a class.

Categories

Resources