How can System.Lazy<T> access private constructor of T? - c#-4.0

I've implemented singleton according to this page using System.Lazy<T>.
I wonder, how technically can System.Lazy<T> access constructor of T, when access modificator of constructor is private.

The Lazy<T> is instantiated with an anonymous method as follows:
new Lazy<Singleton>(() => new Singleton());
Anonymous methods are under the covers just private methods located in the class that defines them. Since this is a method in the class, it is allowed to access any other private members of that class including the private constructor.
The code the C# compiler generates closely resembles the following:
Func<Singleton> factory = this.__compiler_generated_method;
new Lazy<Singleton>(factory);
private static Singleton __compiler_generated_method()
{
return new Singleton();
}

Related

How to instantiate classes only from inside another class in Haxe

I need to prevent class A from being instantiated anywhere but only from another class B, then class B can return the created instance of class A which can be used in any other class.
I understand that B could be a Factory in this example, I looked in the factory pattern in the Haxe code cookbook but it does not seem suit what I am looking for.
In my example class B is doing some work then should return the result in an instance of class A.
no one should be able to create an instance of class A because it is the result of the work that class B performs. anyone needs an instance of A should ask B to do the work and return the resulted A instance
hope I explained it clearly
You would usually do this by using #:allow() metadata in combination with a private constructor:
A.hx:
class A {
#:allow(B)
private function new() {}
}
B.hx:
class B {
public static function create():A {
return new A(); // compiles
}
}
Trying to instantiate A outside of B will result in a compiler error:
class Main {
static function main() {
new A(); // Cannot access private constructor of A
}
}
Note that it's still possible to work around this by using #:access() or #:privateAccess metadata - in Haxe, nothing is ever truly private. It follows a philosophy of "the programmer knows best", which can be very powerful.
Also, you might want to declare A as #:final so nothing can subclass it, because subclasses can access private fields in Haxe. But again, this can be overriden with #:hack metadata.

Why doesn't a Groovy closure have access to injected class member?

We are using Groovy and Guice on a project and I came across the following error:
groovy.lang.MissingPropertyException: No such property: myService for class: com.me.api.services.SomeService$$EnhancerByGuice$$536bdaec
Took a bit to figure out, but it was because I was referencing a private class member, that was injected, inside of a closure. Can anyone shed any light as to why this happens?
Furthermore, is there any better way of doing this?
Here is a snippet of what the class looks like:
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class MyService extends BaseService<Thing> {
#Inject
private ThingDao thingDao
#Inject
private OtherService<Thing> otherService
#Override
List<Thing> findAll() {
List<Thing> things = this.dao.findAll()
things.each {
//Note: This doesn't work!
otherService.doSomething()
}
things
}
I either have to use a standard for loop or not use the injected member which then tends to lead to code duplication.
TLDR;
Either declare otherService public (remove private modifier) or add a getter OtherService<Thing> getOtherService(){otherService}
If you absolutely want to avoid exposing the field through a property, you can do the following trick: create a local variable outside the Closure scope that references your service:
OtherService<Thing> otherService=this.otherService
things.each {
//Note: This will work! Because now there is a local variable in the scope.
//This is handled by normal anonymous inner class mechanisms in the JVM.
otherService.doSomething()
}
Explanation
Under the hood, your closure is an object of an anonymous class, not the object that has your private field, otherService.
This means that it can't resolve a direct reference to the field. Accessing a symbol inside the closure will first look at local variables, and if no match is found, the getProperty() method in Closure will be called to find a property, depending on the resolution strategy that you defined. By default, this is OWNER_FIRST.
If you look the code of Closure#getProperty:
switch(resolveStrategy) {
case DELEGATE_FIRST:
return getPropertyDelegateFirst(property);
case DELEGATE_ONLY:
return InvokerHelper.getProperty(this.delegate, property);
case OWNER_ONLY:
return InvokerHelper.getProperty(this.owner, property);
case TO_SELF:
return super.getProperty(property);
default:
return getPropertyOwnerFirst(property);
}
You see that the owner, delegate and declaring objects need to have matching properties.
In groovy, if you declare a field private, you won't get auto-generated accessor methods, so no properties will be publicly exposed for outside objects.

Code restricting: Create of more than one object in private constructor in C#

I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.

What are 'properties' in Groovy?

Properties in groovy seem like class fields in java without an access modifier. Is that true? Or they have a special meaning. It seems like there is no way to make the properties private?
When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.
class A {
String property
/*
private String property
public void setProperty(String property) { ... }
public String getProperty() { ... }
*/
}
If we declare a public instance variable field we just get a public field, without a setter/getter method pair.
class A {
public String field
/*
public String field
*/
}
From a Groovy client's pov, there is no difference between accessing a Groovy property and a public field at runtime
def a = new A()
println a.field
println a.property
although a.field accesses the instance variable directly and a.property actually calls a.getProperty() (or a.setProperty(...) when assigning a value). But as the property complies to the JavaBeans spec, the class can seamlessly be used in Java-based environments.
I do not see much sense in making a "private property". private restricts the use of a method or instance/class variable to the hosting class type. But maybe you were referring to making a private field instance variable.
Properties can normally be treated like fields, but they are actually backed by implicit getters/setters, so you can still reference them like fields or set them equal to values. Behind the scenes, they are using getters/setters (which you can redefine if you care to).
This page has details on properties/fields and access modifiers (see especially the "Property and field rules" section): https://groovy-lang.org/objectorientation.html#_fields_and_properties
It also shows that you can make a private property (private field backed by private getters/setters), but you have to be explicit in defining the getters/setters.

Using constructors on the Sub New() for a CCW

I'm trying to create a COM Class Library for my VBA Project and one of the limitations I've seemed to have stumbled across is using constructors on the New() subroutine. After creating the new COM class a Public Sub New() is created with the following comments
' A creatable COM class must have a Public Sub New()
' with no parameters, otherwise, the class will not be
' registered in the COM registry and cannot be created
' via CreateObject.
Obviously though I want to create more subroutines with the new keyword that allow for different parameters. However, when I try to do this and implement the objects in VBA I get an error when trying to input the parameters saying "End of statement expected". If anyone has any information that would greatly be appreciated.
Thank you.
All classes exposed to COM must have a parameterless constructor - period. The reason is that when the client instantiates a class the call eventually goes into CoCreateInstance() global function (or IClassFactory::CreateInstance() which is almost the same). CoCreateInstance() (or IClassFactory::CreateInstance()) have no means for passing parameters into the constructor of the class so that class must have a paremeterless constructor - that constructor will be used to instantiate the class internally.
If you need more than a paremeterless constructor - use a factory class. Pseudocode:
// this should be made COM-exposed
interface IYourClassInterface {
};
// this should not be made COM-exposed
class CYourClass {
public:
CYourClass( parameters ) {}
};
class CYourClassFactory {
public:
CYourClassFactory() {} //<- parameterless constructor
IYouClassInterface* CreateInstance( parameters here )
{
return new CYourClass();
}
};
this way you have a factory class with a paremeterless constructor. You instantiate the factory and then call its creator method for instantiating your class.

Resources