Is There a Java Equivalent to C#'s 'Yield' Keyword

Does Java have something like C#'s ref and out keywords?

No, Java doesn't have something like C#'s ref and out keywords for passing by reference.

You can only pass by value in Java. Even references are passed by value. See Jon Skeet's page about parameter passing in Java for more details.

To do something similar to ref or out you would have to wrap your parameters inside another object and pass that object reference in as a parameter.

What is the yield keyword used for in C#?

The yield contextual keyword actually does quite a lot here.

The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}

public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}

When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

Here is a real-life example:

public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}

Is there a yield return in java for lazy fetching in hibernate?

There isn't a yield return statement in Java. The best way (which isn't to say a super easy way) to do what you want is to write your own implementation of Iterator.

class LazyIterator implements Iterator<Foo> {
private Iterator<Foo> backingIterator = null; //set this later

private void lazyLoad() {
if (backingIterator != null) {
return;
}
//load the backing collection and assign to backingIterator here
}

@Override
public boolean hasNext() {
lazyLoad();
return backingIterator.hasNext();
}

@Override
public Foo next() {
lazyLoad();
return backingIterator.next();
}

@Override
public void remove() {
lazyLoad();
backingIterator.remove();
}
}

As you can see, this is an all-or-nothing lazy loader. You might also consider an incremental lazy loader that loads data only as you progress through the collection. One case where this is useful is when the collection contains a very large number of records.

You may also want/need be more specific, and write a lazy loading wrapper of Collection, or List. The technique would be similar, but would generally be more work (a lazy loaded List might need a lazy loded Iterator, and you might have to be concerned with thread safety, just to think of a few things).

This is basically doing by hand what c#'s yield and yield return keywords do under the hood with a compile time transformation.

What is the c# equivalent of ClassAnnotation from java?

While in general answer is NO - there's no compile type check for Type - I believe you can still use generics for your purpose, like this one:

public static void VisitAnnotatedFields<TAttribute>(
MonoBehaviour target,
Action<FieldInfo, TAttribute> closure)
where TAttribute : Attribute
{
IEnumerable<FieldInfo> fieldInfos = target.GetAllFields();
foreach( var iField in fieldInfos ){
object[] customAttributes = iField.GetCustomAttributes(false);
foreach( var jAttr in customAttributes ){
if( jAttr.GetType().IsAssignableFrom(typeof(TAttribute)) ){
closure.Invoke(iField, (TAttribute) jAttr);
}
}
}
}

and call it like this

ReflectionUtils.VisitAnnotatedFields(
target,
(FieldInfo field, NotNullAttribute attr) => {
// do the check for null value and add to failures
});

Which as a bonus will provide you with additional strong type inside closure itself.

C# equivalent to Java's scn.nextInt( )

Is it equivalent to Java's scanner.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?

Yes. Java's Scanner.nextInt() throws an exception when no integer input has been received, as does .NET's int.Parse(Console.ReadLine()).

Is there any benefit to using Math.Floor over explicit integer casting?

Yes, for negative numbers, this works in the opposite way.

Example (using Mono's C# interactive shell csharp):

csharp> Math.Floor(-12.0d)
-12
csharp> Math.Floor(-12.5d)
-13
csharp> (int) -12.5
-12

(same for both Java/C#) and I guess most languages anyway.

Casting a floating-point number to an integer, is performed by throwing away the decimal part maintaining the integer part. The integer part of -12.5 is 12. Thus negative numbers do a Math.Ceil if converted to an int.

Furthermore as @Matthew argues, a float or double can reach numbers like 1.023e23 (Avogadro's constant). Simply because the mantisse can't represent digits after the comma anymore. Numbers that are considered to be an integer anyway, but can't be represented by an int. By performing a Math.floor operation, nothing happens, but the value is still maintained. While conversion to an int could result in overflow:

Example:

csharp> double ac = 1.023e23;
csharp> Math.Floor(ac);
1.023E+23
csharp> (int) ac;
0

Note: this may look far fetched, but there is thus a clear difference in semantics nevertheless. A difference that tends to lead to errors anyway.

In addition, it works differently for infinite numbers and NaN:

System.out.println(Math.floor(Double.POSITIVE_INFINITY)); // Prints Infinity
System.out.println((int)Double.POSITIVE_INFINITY); // Prints 2147483647
System.out.println(Math.floor(Double.NaN)); // Prints NaN
System.out.println((int)Double.NaN); // Prints 0

But I would always use them nevertheless. Casting makes things way more unreadable. Rounding up/down/off is more some kind of (side-effect) of the cast. By using Math.Ceil/Floor/Round it is clear what you mean.

Sometimes a cast to an integer is indeed a bit more efficient than performing a floor/ceil operation first. But a smart compiler can sometimes derive that a variable will always store a positive number and thus optimize it itself. And furthermore for most applications this will result in an insignificant performance penalty.

What's the point of As keyword in C#

They aren't two system of casting. The two have similar actions but very different meanings. An "as" means "I think this object might actually be of this other type; give me null if it isn't." A cast means one of two things:

  • I know for sure that this object actually is of this other type. Make it so, and if I'm wrong, crash the program.

  • I know for sure that this object is not of this other type, but that there is a well-known way of converting the value of the current type to the desired type. (For example, casting int to short.) Make it so, and if the conversion doesn't actually work, crash the program.

See my article on the subject for more details.

https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/



Related Topics



Leave a reply



Submit