Can I set the naming style for parameters specifically in local functions? - resharper

When I'm using local functions in C# I'd like to keep them pure and without being dependent on capturing local variables. Since I can't name my parameters the same as the local variables outside the function, due to name collision, I'd like to prepend them with underscore to have a general working strategy for this.
bool MyLocalFunction(string _str)
{
//...
}
var str = "";
var isValid = MyLocalFunction(str);
Is is possible to make ReSharper enforce this naming in all local functions, while not affecting the naming of parameters in regular methods? I can't find that option in the settings.

If you're using C# 8.0 (.NET Core 3.x and .NET Standard 2.1) then you could use static local functions. For example:
using System;
namespace ConsoleAppLocalFunction
{
public static class Program
{
public static void Main()
{
var first = "Foo";
var last = "Bar";
Console.WriteLine(LocalMethod1("Test", "Message"));
Console.WriteLine(LocalMethod2());
static string LocalMethod1(string first, string last) => first + last;
string LocalMethod2() => first + last;
}
}
}
When you run this the results will be:
TestMessage
FooBar
The LocalMethod1 will use the parameters and doesn't have access to the local variables, LocalMethod2 will use the local variables.
I don't think you can configure ReSharper to use a naming style for local method parameters.

Related

Inline C# Object Creation in F#

I'm trying to interop with a C# library in some F# code. Consider the following C# as though it were the library I'm working with (or skip below to see the actual library I'm working with first):
public class Options
{
public Options(string name)
{
Name = name;
}
public string Name { get; }
public string SomeProperty { get; set; }
}
public class ServiceBuilder
{
public ServiceBuilder ApplyOptions(Options options)
{
//Apply Options in some way
return this;
}
public TheService Build()
{
return new TheService();
}
}
public class TheService
{
}
I'm then trying to create the service but keeping it fluent I have the following F# code:
//Valid Approach but not inlined :(
let options = Options("Test")
options.SomeProperty <- "SomeValue"
let theService =
ServiceBuilder()
.ApplyOptions(options)
.Build();
//Invalid Approach because SomeProperty is not virtual
let theService2 =
ServiceBuilder()
.ApplyOptions({
new Options("Test2") with
member _.SomeProperty = "SomeValue2"
})
.Build()
Is there some way for me to initialize the way I want to inline in F# where I try to create "theService2"? In C# I'd just use Object Intializers. F# Object Expressions are out because I don't have control of the class to make the property virtual.
For additional context in what my C# above is mocking, I'm specifically trying to create a Serilog Logger using the Serilog.Sinks.ElasticSearch nuget package and do roughly the code below in F# (again, inlined if possible):
var loggerConfig = new LoggerConfiguration()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200") ){
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6
});
In F# you can also assign values to properties at initialization, so to create your Options instance in a single expression you can do the following:
Options("Test", SomeProperty="SomeValue")
For direct translation from C# - property initializers are the way to go, as suggested in #rob.earwaker's answer.
However, note also that in F# everything is an expression. There are no "statements" like in C#, every piece of code has a result of some kind. And this also goes for "composite", so to say, pieces of code, such as let blocks. This means, even if you don't feel like using property initializers, you can still do the initialization inline:
let service =
ServiceBuilder()
.ApplyOptions(
let o = Options("Test")
o.SomeProperty <- "SomeValue"
o
)
.Build()
Or using let .. in and a semicolon to put everything on the same line:
let service =
ServiceBuilder()
.WithOptions(let o = Options("Test") in o.SomeProperty <- "SomeValue"; o)
.Build()
Unlike C#, this approach also works for factoring out initializations into reusable pieces:
let service =
ServiceBuilder()
.WithOptions(let o = Options("bar") in mutateSomeOptions(o); mutateOtherOptions(o); o)
.Build()

Haxe / hscript - Prevent exposing certain methods to scripts

So, I've created "interface class" with all static methods, which I want to expose to hscript scripts. It looks like this:
package com.application.interfaces.Terrain;
import com.application.TerrainCore
class Terrain {
private static var terrain:TerrainCore;
public static function _init(inTerrain:TerrainCore):Void {
terrain = inTerrain;
}
public static function test(s:Int):Void {
terrain.test(s);
}
}
The problem is, that I need to set terrain object somehow, but I don't want it to be exposed to scripts. I expose whole classes with
var interp = new Interp();
var module = Type.resolveClass("com.application.interfaces.Terrain");
interp.variables.set("Terrain", module)
The idea was to override method call in hscript.Interp so it doesn't execute any method named _init, but I don't know how to do that. Original call method looks like this:
function call( o : Dynamic, f : Dynamic, args : Array<Dynamic> ) : Dynamic {
return Reflect.callMethod(o,f,args);
}
Can you use a class instance of Terrain instead of using static members? Eg:
interp.variables.set("Terrain", new Terrain(new TerrainCore()));
Script users wont know if they are using static or instance methods as it will still be access via:
Terrain.test(123);
in script.
Another option (based on clemos), is to use rtti to work out what is allowed (instead of maintaining a list of it), eg:
Terrain._init(new TerrainCore());
_init is a private function now, so you need to #:allow it from your calling class (see below), also, you need to annotate with #:rtti so you can grab info about the functions at runtime, so Terrain now looks like:
#:rtti
class Terrain {
private static var terrain:TerrainCore;
#:allow(test.hscript.demo.Main)
private static function _init(inTerrain:TerrainCore):Void {
terrain = inTerrain;
}
public static function test(s:Int):Void {
terrain.test(s);
}
}
Finally, the script interp fcall now honours whether a field is public or private, ie:
public override function fcall(o:Dynamic, f:String, args:Array<Dynamic>):Dynamic
var rtti = haxe.rtti.Rtti.getRtti(o);
for (field in rtti.statics) {
if (field.name == f && field.isPublic == false) {
error(EInvalidAccess(f));
}
}
return super.fcall(o, f, args);
}
Its worth noting that I used statics rather than fields for obvious reasons. Im also not sure what overhead this would cause with the loop and the rtti.
I believe it's fcall you should override, as call is used for toplevel calls only :
https://github.com/HaxeFoundation/hscript/blob/master/hscript/Interp.hx#L328-L331
It should be easy to filter f argument like :
if ( FORBIDDEN_FIELDS.indexOf( f ) > -1 ) throw EInvalidAccess( f );
or
if ( f.indexOf('_') == 0 ) throw EInvalidAccess( f );

Swift2: can extensions make public implementations that manipulate private variables?

I want to create a struct that stores variables that can't be seen directly but can be modified by public functions.
As much as possible, I want to define all this using protocols and extensions with default implementations.
Here's my first try (this can be pasted directly into a Playground):
import Foundation
private protocol VariablesIWantToHide {
var numGerbils: Int { get set }
var numHamsters: Int { get set }
}
protocol MethodsIWantToAccess {
mutating func setGerbilCount(amount: Int)
mutating func setHamsterCount(amount:Int)
}
protocol MultiAccess: VariablesIWantToHide, MethodsIWantToAccess {}
extension MultiAccess {
mutating func setGerbilCount(amount: Int) {
numGerbils = amount
}
mutating func setHamsterCount(amount: Int) {
numHamsters = amount
}
}
struct MultiAccessStruct: MultiAccess {
var numGerbils: Int = 0
var numHamsters: Int = 0
}
This generates the error message error: protocol must be declared private because it refines a private protocol.
The overall goal is the extension MultiAccess part, where I define default public functions that manipulate private variables. Can this be done?
It generates an error message as protocol MultiAccess has an access control of internal since no explicit access control modifier is specified .
Since it refines protocol VariablesIWantToHide which is private , MultiAccess should also be private as per the access control guiding principle which is
"No entity can be defined in terms of another entity that has a lower (more restrictive) access level"
The goal to access private internal variables using public functions cannot be achieved using extensions with default implementation as an extensions access level can always be less than or equal to the class/protocol that it is extending.

How to force the order of Installer Execution

I have been building a new .NET solu­tion with Cas­tle per­form­ing my DI.
Its now at the stage where i would like to con­trol the order in which my installers run. I have built indi­vid­ual classes which implement IWind­sorIn­staller to han­dle my core types — eg IRepos­i­tory, IMap­per and ISer­vice to name a few.
I see that its suggested i implement my own Installer­Fac­tory (guessing i just override Select) in this class.
Then use this new factory in my call to:
FromAssembly.InDirectory(new AssemblyFilter("bin loca­tion"));
My ques­tion — when over­rid­ing the save method — what is the best way to force the order of my installers.
I know its already solved but I couldn't find any example on how to actually implement the InstallerFactory so here's a solution if anyone is googling for it.
How to use:
[InstallerPriority(0)]
public class ImportantInstallerToRunFirst : IWindsorInstaller
{
public void Install(IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
{
// do registrations
}
}
Just add the InstallerPriority attribute with a priority to your "install-order-sensitive" classes. Installers will be sorted by ascending. Installers without priority will default to 100.
How to implement:
public class WindsorBootstrap : InstallerFactory
{
public override IEnumerable<Type> Select(IEnumerable<Type> installerTypes)
{
var retval = installerTypes.OrderBy(x => this.GetPriority(x));
return retval;
}
private int GetPriority(Type type)
{
var attribute = type.GetCustomAttributes(typeof(InstallerPriorityAttribute), false).FirstOrDefault() as InstallerPriorityAttribute;
return attribute != null ? attribute.Priority : InstallerPriorityAttribute.DefaultPriority;
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class InstallerPriorityAttribute : Attribute
{
public const int DefaultPriority = 100;
public int Priority { get; private set; }
public InstallerPriorityAttribute(int priority)
{
this.Priority = priority;
}
}
When starting application, global.asax etc:
container.Install(FromAssembly.This(new WindsorBootstrap()));
You can call your installers in the order they need to be instantiated in Global.asax.cs or e.g. in a Bootstrapper class, which is called from Global.asax.cs.
IWindsorContainer container = new WindsorContainer()
.Install(
new LoggerInstaller() // No dependencies
, new PersistenceInstaller() // --""--
, new RepositoriesInstaller() // Depends on Persistence
, new ServicesInstaller() // Depends on Repositories
, new ControllersInstaller() // Depends on Services
);
They are instantiated in this order, and you can add a breakpoint after and check the container for "Potentially misconfigured components".
If there are any, check their Status->details, if not, it's the correct order.
This solution is quick and easy, the documentation mentions using a InstallerFactory Class for tighter control over your installers so if you have a ton of installers the other solution may fit better. (Using code as convention should not require tons of installers?)
http://docs.castleproject.org/Windsor.Installers.ashx#codeInstallerFactorycode_class_4
In the end i had to use InstallerFactory and implement the ordering rules as suggested previously by returning the IEnumerable<Type> with my specific order

How come the linq syntax work over the IQueryable interface in Rx Framework

I've started looking over the reactive framework. Very nice stuff. But while looking at code samples it got me confused. The linq syntax works with the IQueryable. I thought that linq only works with IEnumerable. On what does the C# compiler bases it's linq to extension methods conversions? Does it require a set of methods with a specific interface?
Not quite. It's just a syntactic translation. For example, the compiler will translate this:
var query = from item in source
select item.Property;
into
var query = source.Select(item => item.Property);
It does that without knowing anything about the Select method. It just does the translation, then tries to compile the translated code.
All the translations are carefully documented in section 7.16 of the C# 4 spec (and the equivalent for earlier editions, of course).
In the case of Rx, it calls the extensions on IObservable<T> and IQbservable<T>. In the case of Parallel Extensions, it calls the extension methods on ParallelQuery<T>.
You can do some mad stuff with it - I have a blog post which gives a few examples. Here's another odd one:
using System;
using System.Linq;
namespace CornerCases
{
class WeirdQueryExpression
{
static WeirdQueryExpression Where(Func<int, int> projection)
{
return new WeirdQueryExpression { Select = ignored => "result!" };
}
Func<Func<string, bool>, string> Select { get; set; }
static void Main()
{
string query = from x in WeirdQueryExpression
where x * 3
select x.Length > 10;
Console.WriteLine(query);
}
}
}
The query translates to:
WeirdQueryExpression.Where(x => x * 3)
.Select(x => x.Length > 10);
... which is a call to a static method, which returns a WeirdQueryExpression, followed by accessing the Where property which returns a Func<Func<string, bool>, string>. We then call that delegate (passing in another delegate) and assign the result to query.
Funky, huh?

Resources