From .Net to Java - c#

Which would be the best way to write the same code in Java?:
Array.Resize(ref DCamposGraficoOperaciones[index].DatosMeses, 12);
I have this code in C# and I have to put it on in Java. Thanks so much. I have a method called resizeDatosMeses in Java to resize the array but when I try to do it in this way:
DCamposGraficoOperaciones[index].getDatosMeses()=resizeDatosMeses(DCamposGraficoOperaciones[index].getDatosMeses(), 12)
I have a mistake which is: The left-hand side of an assignment must be a variable, please could you advice me?
Thanks so much

I suspect you want:
DCamposGraficoOperaciones[index].setDatosMeses(
resizeDatosMeses(DCamposGraficoOperaciones[index].getDatosMeses(), 12));
You can't assign to the result of a method call, which is what you were trying to do before.
I would strongly encourage you to break this line into two separate statements - and also start following Java naming conventions, which would prohibit DCamposGraficoOperaciones as a variable name.
Also, it's not clear why you're resizing an array to start with, but in both .NET and Java you may well be better off using a higher-level abstraction, e.g. List<T> in .NET or ArrayList<T> in Java.

In java you cant re-size arrays. You can use ArrayList and you can add any number of values to it.

Related

Is it possible to change if statement syntax in C#?

I'm new at C# Programming, I just wanna ask if is it possible to change if, else statement syntax in C#?
Example:
Instead of :
a=5;
b=6;
if (a<b)
{
Console.WriteLine("Big");
}
else
{
Console.WriteLine("Small");
}//Output is Small
I would like to change if else statement syntax to other words:
a=5;
b=6;
**say** (a<b)// say is "if"
{
Console.WriteLine("Big");
}
**but**// but is "else"
{
Console.WriteLine("Small");
}//Output is Small
I wanna type it in the textbox and display it in the label
How to do this?
I'm hoping for your help, thank you.
No, you can't change the syntax of C#. It's baked into the language.
Of course, you could check out the Roslyn compiler and build your own "not quite C#" compiler... but I'd strongly advise against it. Why would you want to create a language which no-one but yourself knows how to use, and which has no real advantages over C# other than using a very slightly different vocabulary? You wouldn't be adding anything to the expressive power of the language by doing so.
The answer is NO. You can not achieve this using c#.
And I would suggest why you want to change it I mean its already nicely readable if it is the reason.
And even if you able to do it then also it is not recommended to change the default syntax because it will create confusion for your follow developers.
Extra Note :-
One of the c# operators i tend to use a lot is the ?: operator which is essentially an alternative syntax to an if else statement.
Syntax :
condition ? first_expression : second_expression;
Is equivalent to:
if (condition) {
first_expression;
}
else {
second_expression;
}
You cannot in C#
In C and C++ by using Macros #define you can acheive what you are trying to do. But in C# it donot contain any Macros because
One of main design goals for C# is to keep the code very readable.
Having the ability to write macros gives the programmer the ability to
create their own language - one that doesn't necessarily bear any
relation to what the code underneath. To understand what the code
does, the user must not only understand how the language works, but he
must also understand all of the #define macros that are in effect at
that point in time. That makes code much harder to read.
No. if and else structure persists in many programming languages, so it is accepted globally. I strongly advise not do so.
I have not understood exactly what you want to achieve but maybe you mean the following
Console.WriteLine( a < b ? "Big" : "Small" );
You should read more related to Expression Trees, this provides you with creating code in runtime , then compile and execute. This way your problem can be solved.
http://msdn.microsoft.com/en-us/library/bb397951.aspx

When is it too much "lambda action"?

I often find myself using lambdas as some sort of "local functions" to make my life easier with repetetive operations like those:
Func<string, string> GetText = (resource) => this.resourceManager.GetString(resource);
Func<float, object, string> FormatF1 = (f, o) => String.Format("{0:F1} {1}", f, o);
Func<float, object, string> FormatF2 = (f, o) => String.Format("{0:F2} {1}", f, o);
Instead of writing the String.Format-thing over and over, I can happily blow away with FormatF2 e.g. and save myself time and when I need to change something about the formatting, only one place to make edits.
Especially when I need the functionality in the given function exclusively, I'm very reluctant to turn them into a real function. While the lambdas above were relatively small... sometimes I have larger ones like (the following is supposed to add data to a table for print output):
Action<string, string, string> AddSurfaceData = (resource, col, unit) => {
renderTable.Cells[tableRowIndex, 0].Text = "\t" + this.GetText(resource);
renderTable.Cells[tableRowIndex, 1].Text = FormatF2(paraHydReader.GetFloat(paraHydReader.GetOrdinal(col)), "");
renderTable.Cells[tableRowIndex, 1].Style.TextAlignHorz = C1.C1Preview.AlignHorzEnum.Right;
renderTable.Cells[tableRowIndex, 2].Text = " " + this.GetText(unit);
renderTable.Cells[tableRowIndex, 2].Style.TextAlignHorz = C1.C1Preview.AlignHorzEnum.Left;
++tableRowIndex;
};
Again, I need this often and all the benefits of above apply, too. However, as you can see, this one is quite long for a lambda expression.. the question is: When do you draw the line? Is my last lambda too much? What other ways (other than using real functions or trying to stuff the data in containers and loop over them) exist to avoid writing the same code over and over again?
Thanks in advance
Christian
It is something you use potentially many times within a method, and only that inside that method. I like this idea. Do it if it doesn't make your code hard to read. I would say that you should reconsider if you find it difficult to see what is the content of the lambda function vs. what is the real content of the method. In that case it might be cleaner to pull it out in a separate private method.
At the end, this is really a matter of taste...
I agree with awe: for small scale reuse inside a method (or even a class) this is perfect. Like the string.Format examples. I use this quite often. It's basically the same thing as using a local variable for an intermediate value that you use more than once, but then for code.
Your second example seems to be pushing it a bit. Somehow this gives me the feeling a private method AddSurfaceData (possibly static, depending on its use?) would be a better fit. That is of course outside of the context that you have, so use your own good judgement.
A Lambda method is an anonymous method.
This means that you should not give it a name.
If you are doing that, (in your case, you are assigning a name with your reference), it's just another way to declare a function.
C# has already got a way to declare functions, and it's not the lambda way, which was added
uniquely to pass functions via parameters and returns them as return values.
Think, as an example, in javascript:
function f(var1,var2,...,varX)
{
some code
}
or
var f = function() {
some code
}
Different syntax (almost) same thing.
For more information on why it's not the same thing: Javascript: var functionName = function() {} vs function functionName() {}
Another example: in Haskell You can define two functions:
function1 :: Int -> Int
function1 x = x + 2
or
function2 :: Int -> Int
function2 = \x -> x + 2
Same thing (this time I think it's the very same), different syntax. I prefer the first one, it's more clear.
C# 3.5, as Javascript, has got a lot of functional influences. Some of them should it be used wisely, IMHO.
Someone said local lambda functions with assignment in a reference is a good substitute for a method defined within another method, similar to a "let", or a "where" clause in Haskell.
I say "similar" because the twos have very different semantics, for instance, in Haskell I can use function name which is not declared yet and define it later with "where", while in C#, with function/reference assignment I can't do this.
By the way I think it's a good idea, I'm not banning this use of lambda function, I just want to make people think about it.
Every language has got his abstraction mechanism, use it wisely.
I like the idea. I don't see a better way to maintain code locality without violating the DRY principle. And I think it's only harder to read if you're not accustomed to lambdas.
+1 on nikie re DRY being good in general.
I wouldnt use PascalCase naming for them though.
Be careful though - in most cases the stuff you have in there is just an Extract Method in a dress or a potential helper or extension function. e.g., GetText is a Method and FormatF* is probably a helper method...
I have no problem with the long example. I see that you are repackaging compound data very elegantly.
It's the short ones that will drive your colleagues to investigate the advantages of voluntary institutionalization. Please declare some kind of constant to hold your format string and use "that String.Format-thing over and over". As a C# programmer, I know what that does without looking elsewhere for home-spun functions. That way, when I need to know what the formatted string will look like, I can just examine the constant.
I agree with volothamp in general, but in addition ...
Think of the other people that have to maintain your code. I think this is easier to understand than your first example and still offers the maintenance benefits you mention:
String.Format(this.resourceManager.GetString("BasicFormat"), f, o);
String.Format(this.resourceManager.GetString("AdvancedFormat"), f, o);
And your second example appears to be just a different way to declare a function. I don't see any useful benefit over declaring a helper method. And declaring a helper method will be more understandable to the majority of coders.
I personally think its not in good taste to use lambda functions when there is no need for it. I personally wont use a lambda function to replace a simple few lines of procedural code. Lambda functions offer many enhancements, but make the code slightly more complicated to read.
I wouldnt use it to replace string.format.

Is Resharper correct?

I just installed Reshaper 4.5 and it has come up with the following suggestions:
return this.GetRuleViolations().Count() == 0; -- REMOVE this.
new string[] { this.ID.ToString(), this.Registration } -- REMOVE string, MAKE ANONYMOUS TYPE
int i = Method.GetNumber(); -- REPLACE int WITH var
Should I do these?
I think in some cases it is going to make the code less readable but will it improve performance? what are the benefits of making these changes?
Thanks
1) The explicit this pointer is only necessary when the reference would otherwise be ambiguous. Since GetRuleViolations is defined on the type, you most likely do not need this.
Another point here is that if GetRuleViolations return an IEnumerable of something, you will generally be much better off using Any() instead of Count() == 0 as you risk enumerating the entire sequence.
2) String can be inferred from the initialization.
3) Resharper prefers var over specific types.
Apart from the obvious benefit of your little square going green, if you are writing code that will be maintained by someone else later, it makes good sense not to use your personal preference in coding syntax. Resharper is becoming useful in formatting code in a way that is recognisable to a very wide audience.
I belong to the school of thought that says it doesn't matter who's way is right. If we all stick to a pattern, we'll all find it easier to read each others code.
So, in my humble opinion, don't change the default resharper settings. Just accept that if you use the defaults, you make life simple for everyone.
I think the first one is for the purpose, if you want to make "GetRuleViolations()" a static method. Then you have not to remove the "this" identifier.
For the 3rd one - the one that annoys me the most. It provides the reader with less information and i think it's just a matter of showing off a newish feature.
I'd say - use var when you know the return type and use the correct object type when you do not like this:
var reader = new XmlReader(.... // Implicit
XmlReader reader = SomeClass.GetReader() // Explicit when you can't be sure
First one: Resharper is asking about removing this which is just a style thing to me. Nothing more, keeping it won't harm performance in any way. It is just a matter of readability.
For second and third: Resharper normally prefers using var instead of specific data type, that's why the suggestions. I believe it is a matter of personal choice and provides no extra gain other than readability.
The first seems unclear to me. You usually don't have to prefix this. as long as there are no ambiguities, which I cannot tell from this example. Resharper is probably right. The other two won't improve performance, the compiled result will be the same. It's just a matter of taste and, of course, your coding guidelines.
The first one should be configurable. As far as I remember, you can tell ReSharper whether you want to have "this." in front of only fields, methods, both or none.
Using "var" will not change anything in the generated CIL code, so the performance will stay the same. I haven't used ReSharper for some time and I don't know why it promotes anonymous types so aggressively, but one advantage of "var" is that it's more resistant to change.
Meaning if, instead of calling Method.GetNumber(), you called a wrapper, eg. Filter(Method.GetNumber()) in the same line that returns a Nullable, you won't have to update the variable's type.
None of these will have any effect on performance, only on readability.
I find suggestions 1 and 2 to be more readable, and 3 less readable than your original code.
But you don't need to just follow these suggestions if, e.g., you find them less readable or if they violate your company's code style standard. When you put the cursor on the squiggly line, press Alt-Enter to show the list of Contex Actions. One of them will be to to change the severity of the inspection; you can not show it at all or show it as a hint. You can find a complete list of inspections at ReSharper | Options | Code Inspection | Inspection Severity.

Easily porting Lua code to C#

is there any easy way to port Lua code to C#?
The biggest problem would probably be to port tables neatly in some dictionaries.
And to prevent any misunderstanding: no I cannot use embedded Lua in my program.
Code designed in such a highly dynamic language like Lua would need substantial refactoring to make sense in a static language like C#- the two serve fundamentally different purposes. You would have to re-write such code again from scratch, realistically, unless it used only the most basic features of any language, like basic numerical/string ops.
There's no easy way to do that.
Universal-transpiler can translate a small subset of Lua into several other languages, including C#. This is an example, written for SWI-Prolog:
:- use_module(library(transpiler)).
:- set_prolog_flag(double_quotes,chars).
:- initialization(main).
main :-
translate("function add(a,b) return a + b end function squared(a) return a*a end function add_exclamation_point(parameter) return parameter .. \"!\" end",'lua','c#',X),
atom_chars(Y,X),
writeln(Y).
This is the C# source code that it generates:
public static int add(int a,int b){
return a+b;
}
public static int squared(int a){
return a*a;
}
public static string add_exclamation_point(string parameter){
return parameter+"!";
}
What do you want to achieve? Convert the lua files to C# code, where you want to work with them extensively, or you just want some code that does similar things than the original code.
For the first type of conversion the answer is that it is quite hard, but not impossible. You have to parse the code and re-create the same (dynamic) functionality in C#. Frameworks, like LinFu.Reflection can help here, because they will add some dynamic functionality to CLR.
For the second type, my idea is to convert the lua bytecode to C# instead of the original code. This shouldn't be too hard, mainly because lua doesn't have much opcodes (around 30 if I remember it correctly). From these opcodes the hardest to convert are the logic and jump operators (because you don't have goto in C#), but if you keep the flow operators intact (and convert them to C# - that is more or less accomplishable), and only compile the code between, and convert the result bytecode to C# should do the job. Of course this way you'll lose a lot from the readibility of the original code, and maintaining it will be much harder.
You might also try to find a solution between these two edge cases I've written here. Some constructs can be easily ported (mainly the loops, and simple arithmetic operators), but fall back to the opcode representation for table handling.

Anonymous Instantiation Syntax - Good or Bad?

For quick tasks where I only use an instantiated object once, I am aware that I can do the following:
int FooBarResult = (new Foo()).Bar();
I say this is perfectly acceptable with non-disposable objects and more readable than the alternative:
Foo MyOnceUsedFoo = new Foo();
int FooBarResult = MyOnceUsedFoo.Bar();
Which do you use, and why?
Would you ever use this type of anonymous instantiation in a production app?
Preference: with parenthesis "(new Foo()).Bar();" or without "new Foo().Bar();"?
(Edited to abstract question away from Random class)
Side note regarding random numbers: In fact, no, your specific example (new Random().Next(0,100)) is completely unacceptable. The generated random numbers will be far from uniform.
Other than that, in general, there is not much difference between the two. The compiler will most probably generate the exact same code in either case. You should go with the most readable case (long statements might harm readability; more code will do it too, so you have to make the trade-off in your specific case).
By the way, if you chose to go with the single line case, omit the unnecessary parens (new MyObject().Method() will do).
You might want to consider the implications of using the code in the debugger. The second case will allow you to inspect the object you've created, whereas the first won't. Granted you can always back out to the second case when you're attempting to debug the code.
I've done it both ways and don't really have a preference. I prefer whatever looks more readable, which is highly dependent on the complexity of the class and method being called.
BTW -- you might want to pick a different example. I fear that your point might get lost in discussions over the best way to generate random numbers.
If you are only using the object once, the first way is better all the time.
It is shorter and clearer, because it makes it explicit that you will not use the object later.
It will probably compile to the same CIL anyway, so there's no advantage to the second form.
First statement. It's more readable, has less code and doesn't leave temps around.
The second one is debugging friendly, while the first one isn't. The second wins only because of this.
In fact the first way, creating a temporary, is more readable for two reasons:
1) it's more concise
There's less code to read, there's no unnecessary local variable introduced, and no potential name clash with another local, or shadowing of any variable with the same name in an enclosing scope
2) it communicates something that the second form doesn't, that the object is being used temporarily.
Reading it, I know that that instance is never going to be used again, so in my "mental compiler" that I use to understand the code I'm reading, I don't have to keep a reference to it any more than the code keeps a reference to it.
As Mehrdad notes, though, doing it with a Random class isn't a good idea.
As he also notes, the redundant parentheses make it less concise; unless you're in a dusty corner of a language, assume that competent programmers know the language's operator precedence. In this case, even if I don't know the operator precedence, the alternative parse (calling new on a function's return) is nonsensical, so the "obvious" reading is the correct reading.
int RandomIndex = (new Random()).Next(0,100);
int RandomIndex = new Random().Next(0,100);

Categories

Resources